cocoonstack-sandbox 0.1.20__tar.gz → 0.1.22__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.20 → cocoonstack_sandbox-0.1.22}/PKG-INFO +1 -1
  2. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/conn.py +13 -3
  3. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/errors.py +1 -2
  4. cocoonstack_sandbox-0.1.22/cocoonsandbox/py.typed +0 -0
  5. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/sandbox.py +21 -3
  6. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/template.py +1 -2
  7. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonstack_sandbox.egg-info/PKG-INFO +1 -1
  8. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonstack_sandbox.egg-info/SOURCES.txt +2 -0
  9. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/pyproject.toml +4 -1
  10. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_checkpoint.py +1 -2
  11. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_client.py +28 -37
  12. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_fault_matrix.py +68 -17
  13. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_fixtures.py +7 -8
  14. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_frames.py +1 -3
  15. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_hardening.py +33 -17
  16. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_keepalive.py +64 -86
  17. cocoonstack_sandbox-0.1.22/tests/test_packaging.py +9 -0
  18. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_proc.py +15 -33
  19. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_proxy.py +1 -3
  20. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_volume_controller.py +5 -4
  21. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_wire_binding.py +5 -23
  22. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/LICENSE +0 -0
  23. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/README.md +0 -0
  24. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/__init__.py +0 -0
  25. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/checkpoint.py +0 -0
  26. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/client.py +0 -0
  27. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/endpoint.py +0 -0
  28. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/frames.py +0 -0
  29. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonsandbox/volumes.py +0 -0
  30. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonstack_sandbox.egg-info/dependency_links.txt +0 -0
  31. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/cocoonstack_sandbox.egg-info/top_level.txt +0 -0
  32. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/setup.cfg +0 -0
  33. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_endpoint.py +0 -0
  34. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_stream.py +49 -49
  35. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_upgrade.py +0 -0
  36. {cocoonstack_sandbox-0.1.20 → cocoonstack_sandbox-0.1.22}/tests/test_volumes.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.20
3
+ Version: 0.1.22
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.9
@@ -10,13 +10,15 @@ 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
13
+ from typing import Any, BinaryIO, Protocol, TypeVar, cast
14
14
 
15
15
  from .errors import APIError, ProtocolError, SandboxError, SandboxTimeout, SilkdError
16
16
  from .frames import MAX_FRAME, decode_response, encode_request
17
17
 
18
18
  KEEP_ALIVE_CONNS = 8
19
19
  _FD_SETSIZE = 1024
20
+ _READ_BUFFER = 64 * 1024
21
+ _TCP_KEEPALIVE = {"TCP_KEEPIDLE": 15, "TCP_KEEPALIVE": 15, "TCP_KEEPINTVL": 15, "TCP_KEEPCNT": 9}
20
22
 
21
23
  _CloseableT = TypeVar("_CloseableT", bound="_Closeable")
22
24
 
@@ -194,6 +196,10 @@ def dial_agent(
194
196
  except OSError as exc:
195
197
  raise _handshake_error(f"dial {addr}", exc) from exc
196
198
  sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
199
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
200
+ for opt, setting in _TCP_KEEPALIVE.items():
201
+ if hasattr(socket, opt):
202
+ sock.setsockopt(socket.IPPROTO_TCP, getattr(socket, opt), setting)
197
203
  request = (
198
204
  f"GET /v1/sandboxes/{sandbox_id}/agent HTTP/1.1\r\n"
199
205
  f"Host: {endpoint.netloc}\r\n"
@@ -206,7 +212,7 @@ def dial_agent(
206
212
  try:
207
213
  if endpoint.scheme != "https":
208
214
  sock.settimeout(None)
209
- return Conn(sock, sock.makefile("rb"), request, timeout)
215
+ return Conn(sock, _buffered_reader(sock), request, timeout)
210
216
  context = ssl_context or ssl.create_default_context()
211
217
  sock = context.wrap_socket(sock, server_hostname=host, do_handshake_on_connect=False)
212
218
  sock.settimeout(remaining_timeout(timeout, deadline))
@@ -217,7 +223,7 @@ def dial_agent(
217
223
  # a TLS edge may be a proxy that drops bytes sent ahead of the 101
218
224
  sock.settimeout(remaining_timeout(timeout, deadline))
219
225
  sock.sendall(request)
220
- reader = sock.makefile("rb")
226
+ reader = _buffered_reader(sock)
221
227
  _read_upgrade(reader, lambda: sock.settimeout(remaining_timeout(timeout, deadline)))
222
228
  remaining_timeout(timeout, deadline)
223
229
  sock.settimeout(None)
@@ -255,6 +261,10 @@ def is_quiet(sock: socket.socket | None) -> bool:
255
261
  return False
256
262
 
257
263
 
264
+ def _buffered_reader(sock: socket.socket) -> BinaryIO:
265
+ return cast(BinaryIO, sock.makefile("rb", buffering=_READ_BUFFER))
266
+
267
+
258
268
  def _handshake_error(what: str, exc: OSError) -> SandboxError:
259
269
  if isinstance(exc, (TimeoutError, socket.timeout)):
260
270
  return SandboxTimeout(f"{what} timed out")
@@ -45,8 +45,7 @@ class SilkdError(SandboxError):
45
45
 
46
46
 
47
47
  class ExitError(SandboxError):
48
- """A command exited non-zero; carries the exit code, stderr, and whatever
49
- stdout it had produced — a failing build's log is on stdout."""
48
+ """A command exited non-zero; carries the code, stderr, and the stdout produced before it failed."""
50
49
 
51
50
  def __init__(self, code: int, stderr: str, stdout: str = "") -> None:
52
51
  super().__init__(f"exit status {code}: {stderr.strip()}")
File without changes
@@ -140,6 +140,8 @@ class Sandbox:
140
140
  """Streams raw output bytes and returns the exit code; timeout bounds the call and kills what it cuts."""
141
141
  if timeout is not None and timeout <= 0:
142
142
  raise ValueError("timeout must be positive")
143
+ if stdin and not isinstance(stdin, (bytes, bytearray, memoryview)):
144
+ raise TypeError("stdin must be bytes")
143
145
  deadline = None if timeout is None else time.monotonic() + timeout
144
146
  expired = threading.Event()
145
147
  started: deque[int] = deque(maxlen=1)
@@ -408,12 +410,28 @@ class Sandbox:
408
410
  """Releases the sandbox; its VM is destroyed."""
409
411
  self._pool.drain()
410
412
  try:
411
- self._client._request(
412
- self.owner, "POST", f"/v1/sandboxes/{self.id}/release", None, "release", bearer=self.token
413
- )
413
+ self._release_at(self.owner)
414
+ return
415
+ except APIError as exc:
416
+ if exc.status not in (0, 404):
417
+ raise
418
+ unreachable = exc if exc.status == 0 else None
419
+ try:
420
+ moved = self._client.lookup(self.id, self.token)
414
421
  except APIError as exc:
422
+ if unreachable is not None:
423
+ raise unreachable from None
415
424
  if exc.status != 404:
416
425
  raise
426
+ return
427
+ try:
428
+ self._release_at(moved.owner)
429
+ except APIError as exc:
430
+ if exc.status != 404:
431
+ raise
432
+
433
+ def _release_at(self, addr: str) -> None:
434
+ self._client._request(addr, "POST", f"/v1/sandboxes/{self.id}/release", None, "release", bearer=self.token)
417
435
 
418
436
  def _volumes_request(
419
437
  self, method: str, body: dict[str, Any] | None, verb: str, timeout: float | None
@@ -31,8 +31,7 @@ class Template:
31
31
  *,
32
32
  deadline: float | None = None,
33
33
  ) -> Sandbox:
34
- """Claims the template, following placement when volumes require it.
35
- mount=False attaches the volumes without mounting them."""
34
+ """Claims the template, following placement when volumes require it; mount=False attaches them unmounted."""
36
35
  claim = _claim_body(self.name, self.net, self.size, ttl_seconds, volumes, mount)
37
36
  claim["require_promoted"] = True
38
37
  if volumes:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.20
3
+ Version: 0.1.22
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.9
@@ -8,6 +8,7 @@ cocoonsandbox/conn.py
8
8
  cocoonsandbox/endpoint.py
9
9
  cocoonsandbox/errors.py
10
10
  cocoonsandbox/frames.py
11
+ cocoonsandbox/py.typed
11
12
  cocoonsandbox/sandbox.py
12
13
  cocoonsandbox/template.py
13
14
  cocoonsandbox/volumes.py
@@ -23,6 +24,7 @@ tests/test_fixtures.py
23
24
  tests/test_frames.py
24
25
  tests/test_hardening.py
25
26
  tests/test_keepalive.py
27
+ tests/test_packaging.py
26
28
  tests/test_proc.py
27
29
  tests/test_proxy.py
28
30
  tests/test_stream.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cocoonstack-sandbox"
7
- version = "0.1.20"
7
+ version = "0.1.22"
8
8
  description = "Python SDK for the cocoon sandbox control plane"
9
9
  requires-python = ">=3.9"
10
10
  license = { text = "Apache-2.0" }
@@ -13,6 +13,9 @@ readme = "README.md"
13
13
  [tool.setuptools.packages.find]
14
14
  include = ["cocoonsandbox*"]
15
15
 
16
+ [tool.setuptools.package-data]
17
+ cocoonsandbox = ["py.typed"]
18
+
16
19
  [tool.pytest.ini_options]
17
20
  pythonpath = ["."]
18
21
 
@@ -1,5 +1,4 @@
1
- """Checkpoint claim redirect: mirrors the cluster redirect follow tested for
2
- Client.new in test_fault_matrix.py, applied to Checkpoint.new."""
1
+ """Checkpoint claim redirect, mirroring the Client.new redirect in test_fault_matrix.py."""
3
2
 
4
3
  import pytest
5
4
 
@@ -2,10 +2,10 @@
2
2
 
3
3
  import threading
4
4
  import time
5
- from http.server import HTTPServer, ThreadingHTTPServer
5
+ from http.server import ThreadingHTTPServer
6
6
 
7
7
  import pytest
8
- from conftest import FakeNode, sandbox_at
8
+ from conftest import FakeNode, sandbox_at, wait_until
9
9
 
10
10
  from cocoonsandbox import APIError, Client, Template
11
11
 
@@ -14,27 +14,29 @@ class KeptNode(FakeNode):
14
14
  protocol_version = "HTTP/1.1"
15
15
  conns = 0
16
16
  drop_after_reply = False
17
+ closed = 0
17
18
 
18
19
  def setup(self):
19
20
  super().setup()
20
21
  KeptNode.conns += 1
21
22
 
23
+ def finish(self):
24
+ super().finish()
25
+ self.connection.close()
26
+ KeptNode.closed += 1
27
+
22
28
  def _reply(self, code, payload):
23
29
  super()._reply(code, payload)
24
30
  self.close_connection = self.drop_after_reply
25
31
 
26
32
 
27
33
  @pytest.fixture
28
- def node():
29
- server = HTTPServer(("127.0.0.1", 0), FakeNode)
34
+ def node(spawn_node):
30
35
  FakeNode.routes = {}
31
- thread = threading.Thread(target=server.serve_forever, daemon=True)
32
- thread.start()
33
- yield f"127.0.0.1:{server.server_port}"
34
- server.shutdown()
36
+ return spawn_node(FakeNode.routes)
35
37
 
36
38
 
37
- def test_claim_happy_path(node):
39
+ def test_claim_returns_the_sandbox_with_its_owner_and_digest(node):
38
40
  FakeNode.routes[("POST", "/v1/claim")] = lambda body, path: (
39
41
  200,
40
42
  {"id": "sb_1", "token": "tok", "owner_addr": node, "template_digest": "sha256:task"},
@@ -196,20 +198,6 @@ def test_template_volume_claim_follows_redirect(node):
196
198
  assert sb.volumes == seen[1]["volumes"]
197
199
 
198
200
 
199
- def test_volume_catalog(node):
200
- want = [
201
- {
202
- "name": "imagenet",
203
- "default_mount": "/volumes/imagenet",
204
- "size_bytes": 42,
205
- "available": True,
206
- "nodes": 3,
207
- }
208
- ]
209
- FakeNode.routes[("GET", "/v1/volumes")] = lambda body, path: (200, {"volumes": want})
210
- assert Client(node).volumes() == want
211
-
212
-
213
201
  def test_volume_catalog_surfaces_writable(node):
214
202
  want = [
215
203
  {
@@ -345,19 +333,11 @@ def test_claim_deadline_bounds_the_redirect_walk(node, black_hole):
345
333
 
346
334
  def test_claim_deadline_bounds_the_entry_node(black_hole):
347
335
  client = Client(black_hole, timeout=2.0)
336
+ started = time.monotonic()
348
337
  with pytest.raises(TimeoutError):
349
- client.new("rt:24.04", deadline=time.monotonic() + 0.3)
350
-
351
-
352
- def recording_claim(reply):
353
- seen = []
354
-
355
- def claim(body, path):
356
- seen.append(body)
357
- return 200, reply
358
-
359
- FakeNode.routes[("POST", "/v1/claim")] = claim
360
- return seen
338
+ client.new("rt:24.04", deadline=started + 0.3)
339
+ elapsed = time.monotonic() - started
340
+ assert elapsed < 1.5, elapsed
361
341
 
362
342
 
363
343
  @pytest.mark.parametrize(("keep_alive", "conns"), [(30.0, 1), (0, 2)])
@@ -374,7 +354,7 @@ def test_a_parked_connection_the_node_closed_is_not_reused(kept_node, fd_floor):
374
354
  KeptNode.drop_after_reply = True
375
355
  client = Client(kept_node)
376
356
  client.new("rt:24.04")
377
- time.sleep(0.1)
357
+ wait_until(lambda: KeptNode.closed == 1, "the node never closed the connection")
378
358
  assert client.new("rt:24.04").id == "sb_1"
379
359
  assert KeptNode.conns == 2
380
360
 
@@ -382,7 +362,18 @@ def test_a_parked_connection_the_node_closed_is_not_reused(kept_node, fd_floor):
382
362
  @pytest.fixture
383
363
  def kept_node():
384
364
  server = ThreadingHTTPServer(("127.0.0.1", 0), KeptNode)
385
- KeptNode.routes, KeptNode.conns, KeptNode.drop_after_reply = {}, 0, False
365
+ KeptNode.routes, KeptNode.conns, KeptNode.closed, KeptNode.drop_after_reply = {}, 0, 0, False
386
366
  threading.Thread(target=server.serve_forever, daemon=True).start()
387
367
  yield f"127.0.0.1:{server.server_port}"
388
368
  server.shutdown()
369
+
370
+
371
+ def recording_claim(reply):
372
+ seen = []
373
+
374
+ def claim(body, path):
375
+ seen.append(body)
376
+ return 200, reply
377
+
378
+ FakeNode.routes[("POST", "/v1/claim")] = claim
379
+ return seen
@@ -1,10 +1,5 @@
1
- """Fault matrix for the cluster redirect follow and the lookup scatter:
2
- dead first candidate (connection refused), 404 first candidate, a definitive
3
- candidate error that still tries the next one, every candidate exhausted
4
- (then the origin fallback heals, fails, or is skipped for a definitive
5
- error) — and lookup must not pay a hung or dead peer's full timeout."""
1
+ """Fault matrix for the cluster redirect follow and the lookup scatter."""
6
2
 
7
- import socket
8
3
  import time
9
4
 
10
5
  import pytest
@@ -12,15 +7,6 @@ import pytest
12
7
  from cocoonsandbox import APIError, Client
13
8
 
14
9
 
15
- @pytest.fixture
16
- def hung_addr():
17
- sock = socket.socket()
18
- sock.bind(("127.0.0.1", 0))
19
- sock.listen(1)
20
- yield f"127.0.0.1:{sock.getsockname()[1]}"
21
- sock.close()
22
-
23
-
24
10
  def test_claim_redirect_skips_dead_candidate(spawn_node, dead_addr):
25
11
  good = spawn_node({("POST", "/v1/claim"): lambda body, path: (200, {"id": "sb_ok", "token": "t"})})
26
12
  entry = spawn_node({("POST", "/v1/claim"): lambda body, path: (200, {"redirect": [dead_addr, good]})})
@@ -184,12 +170,12 @@ def test_lookup_dead_peer_resolves_fast(spawn_node, dead_addr):
184
170
  assert elapsed < 2.0, elapsed
185
171
 
186
172
 
187
- def test_lookup_hung_peer_resolves_fast(spawn_node, hung_addr):
173
+ def test_lookup_hung_peer_resolves_fast(spawn_node, black_hole):
188
174
  owner = spawn_node({("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (200, {"owner_addr": "10.0.0.9:7777"})})
189
175
  entry = spawn_node(
190
176
  {
191
177
  ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (404, {"error": "not here"}),
192
- ("GET", "/v1/peers"): lambda body, path: (200, {"peers": [hung_addr, owner]}),
178
+ ("GET", "/v1/peers"): lambda body, path: (200, {"peers": [black_hole, owner]}),
193
179
  }
194
180
  )
195
181
  start = time.monotonic()
@@ -209,3 +195,68 @@ def test_lookup_all_miss(spawn_node, dead_addr):
209
195
  with pytest.raises(APIError) as exc:
210
196
  Client(entry).lookup("sb_1", "tok")
211
197
  assert exc.value.status == 404 and "no owner found" in exc.value.message
198
+
199
+
200
+ def test_close_releases_a_sandbox_that_moved(spawn_node):
201
+ released = []
202
+
203
+ def release(body, path):
204
+ released.append(path)
205
+ return (204, {})
206
+
207
+ adopter = spawn_node(
208
+ {
209
+ ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (200, {}),
210
+ ("POST", "/v1/sandboxes/sb_1/release"): release,
211
+ }
212
+ )
213
+ old = spawn_node(
214
+ {
215
+ ("POST", "/v1/sandboxes/sb_1/release"): lambda body, path: (404, {"error": "unknown sandbox"}),
216
+ ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (404, {"error": "not here"}),
217
+ ("GET", "/v1/peers"): lambda body, path: (200, {"peers": [adopter]}),
218
+ }
219
+ )
220
+ Client(old).attach(old, "sb_1", "tok").close()
221
+ assert released
222
+
223
+
224
+ def test_close_follows_a_move_off_a_retired_node(spawn_node, dead_addr):
225
+ released = []
226
+
227
+ def release(body, path):
228
+ released.append(path)
229
+ return (204, {})
230
+
231
+ adopter = spawn_node(
232
+ {
233
+ ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (200, {}),
234
+ ("POST", "/v1/sandboxes/sb_1/release"): release,
235
+ ("GET", "/v1/peers"): lambda body, path: (200, {"peers": []}),
236
+ }
237
+ )
238
+ Client(adopter).attach(dead_addr, "sb_1", "tok").close()
239
+ assert released
240
+
241
+
242
+ def test_close_reports_a_retired_node_when_no_node_holds_the_sandbox(spawn_node, dead_addr):
243
+ entry = spawn_node(
244
+ {
245
+ ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (404, {"error": "not here"}),
246
+ ("GET", "/v1/peers"): lambda body, path: (200, {"peers": []}),
247
+ }
248
+ )
249
+ with pytest.raises(APIError) as exc:
250
+ Client(entry).attach(dead_addr, "sb_1", "tok").close()
251
+ assert exc.value.status == 0, exc.value
252
+
253
+
254
+ def test_close_of_a_sandbox_no_node_holds_is_not_an_error(spawn_node):
255
+ gone = spawn_node(
256
+ {
257
+ ("POST", "/v1/sandboxes/sb_1/release"): lambda body, path: (404, {"error": "unknown sandbox"}),
258
+ ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (404, {"error": "not here"}),
259
+ ("GET", "/v1/peers"): lambda body, path: (200, {"peers": []}),
260
+ }
261
+ )
262
+ Client(gone).attach(gone, "sb_1", "tok").close()
@@ -1,8 +1,6 @@
1
- """Round-trips the shared protocol fixture corpus, the same drift guard the
2
- Rust and Go implementations run: every request fixture must re-encode
3
- byte-for-byte (up to key order) through frames.encode_request, and every
4
- response fixture must decode."""
1
+ """Round-trips the protocol fixture corpus, the same drift guard the Rust and Go implementations run."""
5
2
 
3
+ import base64
6
4
  import json
7
5
  import pathlib
8
6
 
@@ -22,7 +20,7 @@ def fixture_files(prefix):
22
20
  @pytest.mark.parametrize("path", fixture_files("req_"), ids=lambda p: p.stem)
23
21
  def test_request_round_trip(path):
24
22
  want = json.loads(path.read_text())
25
- fields = {k: v for k, v in want.items() if k not in ("v", "op")}
23
+ fields = {k: base64.b64decode(v) if k == "data" else v for k, v in want.items() if k not in ("v", "op")}
26
24
  got = json.loads(frames.encode_request(want["op"], **fields))
27
25
  assert got == want
28
26
 
@@ -30,7 +28,8 @@ def test_request_round_trip(path):
30
28
  @pytest.mark.parametrize("path", fixture_files("resp_"), ids=lambda p: p.stem)
31
29
  def test_response_decodes(path):
32
30
  raw = path.read_text().encode()
31
+ want = json.loads(raw)
33
32
  frame = frames.decode_response(raw)
34
- assert frame["type"] == json.loads(raw)["type"]
35
- if "data" in json.loads(raw):
36
- assert isinstance(frame["data"], bytes)
33
+ assert frame["type"] == want["type"]
34
+ if "data" in want:
35
+ assert frame["data"] == base64.b64decode(want["data"])
@@ -1,6 +1,4 @@
1
- """Guards the fast bulk slicer in frames.decode_response: a "data" match
2
- inside a nested unknown field or trailing bytes after the frame must never
3
- yield a silently wrong payload — unexpected shapes take the full parse."""
1
+ """Guards the fast bulk slicer in decode_response: unexpected shapes take the full parse."""
4
2
 
5
3
  import base64
6
4
  import json
@@ -37,6 +37,14 @@ def test_dial_agent_wraps_refused_connection(dead_addr):
37
37
  dial_agent(dead_addr, "sb_1", "tok", 0.5)
38
38
 
39
39
 
40
+ def test_dial_agent_enables_tcp_keepalive(black_hole):
41
+ with dial_agent(black_hole, "sb_1", "tok", 0.5) as conn:
42
+ assert conn._sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)
43
+ for idle in ("TCP_KEEPIDLE", "TCP_KEEPALIVE"):
44
+ if hasattr(socket, idle):
45
+ assert conn._sock.getsockopt(socket.IPPROTO_TCP, getattr(socket, idle)) == 15, idle
46
+
47
+
40
48
  def test_send_on_a_dead_socket_raises_a_typed_error():
41
49
  ours, theirs = socket.socketpair()
42
50
  theirs.close()
@@ -48,21 +56,21 @@ def test_send_on_a_dead_socket_raises_a_typed_error():
48
56
  conn.close()
49
57
 
50
58
 
51
- def test_watcher_propagates_silkd_error():
52
- client_sock, guest_sock = socket.socketpair()
59
+ def test_watcher_propagates_silkd_error(conn_pair):
60
+ conn, guest_sock = conn_pair
53
61
  guest_sock.sendall(json.dumps({"type": "error", "kind": "not_found", "message": "gone"}).encode() + b"\n")
54
62
  guest_sock.close()
55
- watcher = Watcher(Conn(client_sock, client_sock.makefile("rb")))
63
+ watcher = Watcher(conn)
56
64
  with pytest.raises(SilkdError):
57
65
  for _ in watcher:
58
66
  pass
59
67
 
60
68
 
61
- def test_watcher_ends_cleanly_on_garbage_frame():
62
- client_sock, guest_sock = socket.socketpair()
69
+ def test_watcher_ends_cleanly_on_garbage_frame(conn_pair):
70
+ conn, guest_sock = conn_pair
63
71
  guest_sock.sendall(b"not json at all\n")
64
72
  guest_sock.close()
65
- watcher = Watcher(Conn(client_sock, client_sock.makefile("rb")))
73
+ watcher = Watcher(conn)
66
74
  assert list(watcher) == []
67
75
 
68
76
 
@@ -95,19 +103,19 @@ def test_empty_claim_reply_is_an_api_error(spawn_node):
95
103
  Client(addr).new("rt:24.04")
96
104
 
97
105
 
98
- def test_pty_read_returns_empty_after_the_exit_frame():
99
- client_sock, guest_sock = socket.socketpair()
106
+ def test_pty_read_returns_empty_after_the_exit_frame(conn_pair):
107
+ conn, guest_sock = conn_pair
100
108
  guest_sock.sendall(json.dumps({"type": "exit", "code": 3}).encode() + b"\n")
101
109
  guest_sock.close()
102
- pty = Pty(sandbox_at("127.0.0.1:1"), Conn(client_sock, client_sock.makefile("rb")), 1)
110
+ pty = Pty(sandbox_at("127.0.0.1:1"), conn, 1)
103
111
  assert pty.read() == b""
104
112
  assert pty.exit_code == 3
105
113
  assert pty.read() == b""
106
114
 
107
115
 
108
- def test_pty_write_chunks_a_large_buffer():
109
- client_sock, guest_sock = socket.socketpair()
110
- pty = Pty(sandbox_at("127.0.0.1:1"), Conn(client_sock, client_sock.makefile("rb")), 1)
116
+ def test_pty_write_chunks_a_large_buffer(conn_pair):
117
+ conn, guest_sock = conn_pair
118
+ pty = Pty(sandbox_at("127.0.0.1:1"), conn, 1)
111
119
  frames = []
112
120
 
113
121
  def drain():
@@ -145,10 +153,10 @@ def test_session_and_lsp_close_twice(monkeypatch):
145
153
  Session(sb, "s1").close()
146
154
 
147
155
 
148
- def test_watcher_error_stays_none_after_close():
149
- client_sock, guest_sock = socket.socketpair()
156
+ def test_watcher_error_stays_none_after_close(conn_pair):
157
+ conn, guest_sock = conn_pair
150
158
  guest_sock.sendall(json.dumps({"type": "ready"}).encode() + b"\n")
151
- watcher = Watcher(Conn(client_sock, client_sock.makefile("rb")))
159
+ watcher = Watcher(conn)
152
160
  events = []
153
161
  consumer = threading.Thread(target=lambda: events.extend(watcher), daemon=True)
154
162
  consumer.start()
@@ -194,10 +202,18 @@ def test_dial_timeout_bounds_the_whole_upgrade() -> None:
194
202
  threading.Thread(target=slow_headers, daemon=True).start()
195
203
  addr = f"127.0.0.1:{server.getsockname()[1]}"
196
204
  started = time.monotonic()
197
- with pytest.raises(SandboxTimeout), dial_agent(addr, "sb_x", "tok", timeout=0.2) as conn:
205
+ with server, pytest.raises(SandboxTimeout), dial_agent(addr, "sb_x", "tok", timeout=0.2) as conn:
198
206
  conn.send("info")
199
207
  conn.recv()
200
208
  assert time.monotonic() - started < 0.6, (
201
209
  "each header arrived under the per-read timeout; only a whole-dial budget stops this"
202
210
  )
203
- server.close()
211
+
212
+
213
+ @pytest.fixture
214
+ def conn_pair():
215
+ client_sock, guest_sock = socket.socketpair()
216
+ conn = Conn(client_sock, client_sock.makefile("rb"))
217
+ yield conn, guest_sock
218
+ conn.close()
219
+ guest_sock.close()
@@ -5,7 +5,6 @@ import contextlib
5
5
  import json
6
6
  import socket
7
7
  import threading
8
- import time
9
8
 
10
9
  import pytest
11
10
  from conftest import accept_upgrade, sandbox_at, wait_until
@@ -75,127 +74,106 @@ class FakeAgent:
75
74
  return [{"type": "error", "kind": "unimplemented", "message": op}]
76
75
 
77
76
 
78
- def test_calls_share_one_connection(fd_floor):
79
- agent = FakeAgent()
80
- sb = sandbox_at(agent.addr)
81
- try:
82
- for _ in range(3):
83
- assert sb.stat("/")["kind"] == "dir"
84
- assert sb.exec("echo", "42") == "42\n"
85
- assert sb._pool._parked[0][1]._sock.fileno() >= fd_floor
86
- finally:
87
- sb._pool.drain()
88
- agent.stop()
77
+ def test_calls_share_one_connection(fd_floor, relay):
78
+ agent, sb = relay()
79
+ for _ in range(3):
80
+ assert sb.stat("/")["kind"] == "dir"
81
+ assert sb.exec("echo", "42") == "42\n"
82
+ assert sb._pool._parked[0][1]._sock.fileno() >= fd_floor
89
83
  assert agent.upgrades == 1, agent.upgrades
90
84
 
91
85
 
92
- def test_a_refused_stream_open_keeps_its_connection():
93
- agent = FakeAgent()
94
- sb = sandbox_at(agent.addr)
95
- try:
96
- for _ in range(3):
97
- with pytest.raises(SilkdError):
98
- sb.watch("/missing")
99
- finally:
100
- sb._pool.drain()
101
- agent.stop()
86
+ def test_a_refused_stream_open_keeps_its_connection(relay):
87
+ agent, sb = relay()
88
+ for _ in range(3):
89
+ with pytest.raises(SilkdError):
90
+ sb.watch("/missing")
102
91
  assert agent.upgrades == 1
103
92
 
104
93
 
105
- def test_old_daemon_dials_per_call():
106
- agent = FakeAgent(proto=1)
107
- sb = sandbox_at(agent.addr)
108
- try:
109
- for _ in range(3):
110
- assert sb.exec("echo", "42") == "42\n"
111
- finally:
112
- agent.stop()
94
+ def test_old_daemon_dials_per_call(relay):
95
+ agent, sb = relay(proto=1)
96
+ for _ in range(3):
97
+ assert sb.exec("echo", "42") == "42\n"
113
98
  assert agent.upgrades == 4, "the proto probe plus one dial per call"
114
99
 
115
100
 
116
- def test_old_daemon_that_closes_after_info_gets_the_request_on_a_redial():
117
- agent = FakeAgent(proto=1, slam=True)
118
- sb = sandbox_at(agent.addr)
119
- try:
120
- for _ in range(2):
121
- assert sb.stat("/")["kind"] == "dir"
122
- finally:
123
- agent.stop()
101
+ def test_old_daemon_that_closes_after_info_gets_the_request_on_a_redial(relay):
102
+ agent, sb = relay(proto=1, slam=True)
103
+ for _ in range(2):
104
+ assert sb.stat("/")["kind"] == "dir"
124
105
  assert agent.upgrades == 3, "the proto probe plus one dial per call"
125
106
 
126
107
 
127
- def test_keep_alive_off_dials_per_call():
128
- agent = FakeAgent()
129
- sb = sandbox_at(agent.addr, keep_alive=0)
130
- try:
131
- for _ in range(3):
132
- sb.stat("/")
133
- finally:
134
- agent.stop()
108
+ def test_keep_alive_off_dials_per_call(relay):
109
+ agent, sb = relay(keep_alive=0)
110
+ for _ in range(3):
111
+ sb.stat("/")
135
112
  assert agent.upgrades == 3
136
113
 
137
114
 
138
- def test_idle_connection_closes():
139
- agent = FakeAgent()
140
- sb = sandbox_at(agent.addr, keep_alive=0.05)
141
- try:
142
- sb.stat("/")
143
- wait_until(lambda: agent.closed == 1, "idle connection still open after the keep-alive window")
144
- finally:
145
- sb._pool.drain()
146
- agent.stop()
115
+ def test_idle_connection_closes(relay):
116
+ agent, sb = relay(keep_alive=0.05)
117
+ sb.stat("/")
118
+ wait_until(lambda: agent.closed == 1, "idle connection still open after the keep-alive window")
147
119
 
148
120
 
149
- def test_peer_hang_up_is_noticed_before_reuse(fd_floor):
150
- agent = FakeAgent(hang_up_after=2)
151
- sb = sandbox_at(agent.addr)
152
- try:
153
- sb.stat("/")
154
- wait_until(lambda: agent.hangups == 1, "the fake never hung up")
155
- assert sb.stat("/")["kind"] == "dir"
156
- finally:
157
- sb._pool.drain()
158
- agent.stop()
121
+ def test_peer_hang_up_is_noticed_before_reuse(fd_floor, relay):
122
+ agent, sb = relay(hang_up_after=2)
123
+ sb.stat("/")
124
+ wait_until(lambda: agent.hangups == 1, "the fake never hung up")
125
+ assert sb.stat("/")["kind"] == "dir"
159
126
  assert agent.upgrades == 2
160
127
 
161
128
 
162
129
  def test_run_timeout_bounds_the_proto_probe():
163
130
  server = socket.create_server(("127.0.0.1", 0))
131
+ cut = threading.Event()
164
132
 
165
133
  def serve():
166
134
  conn, _ = server.accept()
167
- accept_upgrade(conn)
168
- time.sleep(3)
169
- conn.close()
135
+ conn.settimeout(3)
136
+ with conn, contextlib.suppress(OSError):
137
+ reader = accept_upgrade(conn)
138
+ while reader.readline():
139
+ pass
140
+ cut.set()
170
141
 
171
142
  threading.Thread(target=serve, daemon=True).start()
172
143
  sb = sandbox_at(f"127.0.0.1:{server.getsockname()[1]}")
173
- started = time.monotonic()
174
144
  try:
175
145
  with pytest.raises(TimeoutError):
176
146
  sb.run(["true"], timeout=0.5)
147
+ assert cut.wait(1), "the unanswered info probe outlived the run timeout"
177
148
  finally:
178
149
  server.close()
179
- assert time.monotonic() - started < 2, "the unanswered info probe outlived the run timeout"
180
150
 
181
151
 
182
- def test_close_drains_the_parked_connection(monkeypatch):
183
- agent = FakeAgent()
184
- sb = sandbox_at(agent.addr)
152
+ def test_close_drains_the_parked_connection(monkeypatch, relay):
153
+ agent, sb = relay()
185
154
  monkeypatch.setattr(sb._client, "_request", lambda *args, **kwargs: {})
186
- try:
187
- sb.stat("/")
188
- sb.close()
189
- wait_until(lambda: agent.closed == 1, "parked connection survived close")
190
- finally:
191
- agent.stop()
155
+ sb.stat("/")
156
+ sb.close()
157
+ wait_until(lambda: agent.closed == 1, "parked connection survived close")
192
158
 
193
159
 
194
- def test_an_upload_an_old_daemon_rejects_raises_its_error_frame():
195
- agent = FakeAgent(proto=1, slam=True)
196
- sb = sandbox_at(agent.addr)
197
- try:
198
- with pytest.raises(SilkdError):
199
- sb.write_file("/missing/f", bytes(64 << 20))
200
- finally:
160
+ def test_an_upload_an_old_daemon_rejects_raises_its_error_frame(relay):
161
+ _, sb = relay(proto=1, slam=True)
162
+ with pytest.raises(SilkdError):
163
+ sb.write_file("/missing/f", bytes(64 << 20))
164
+
165
+
166
+ @pytest.fixture
167
+ def relay():
168
+ started = []
169
+
170
+ def start(proto=KEEP_ALIVE_PROTO, hang_up_after=0, slam=False, **client_kwargs):
171
+ agent = FakeAgent(proto, hang_up_after, slam)
172
+ sb = sandbox_at(agent.addr, **client_kwargs)
173
+ started.append((agent, sb))
174
+ return agent, sb
175
+
176
+ yield start
177
+ for agent, sb in started:
178
+ sb._pool.drain()
201
179
  agent.stop()
@@ -0,0 +1,9 @@
1
+ """The package carries the PEP 561 marker so consumers' type checkers read its annotations."""
2
+
3
+ import pathlib
4
+
5
+ import cocoonsandbox
6
+
7
+
8
+ def test_package_ships_the_pep561_marker():
9
+ assert (pathlib.Path(cocoonsandbox.__file__).parent / "py.typed").is_file()
@@ -1,10 +1,9 @@
1
- """Process-management verbs against a scripted fake conn: pure frame
2
- plumbing, so the fake pins the framing and terminal semantics."""
1
+ """Process-management verbs against a scripted fake conn, which pins the framing and terminal semantics."""
3
2
 
4
3
  import threading
5
4
 
6
5
  import pytest
7
- from conftest import sandbox_at
6
+ from conftest import FakeConn, sandbox_at
8
7
 
9
8
  from cocoonsandbox import ProtocolError
10
9
  from cocoonsandbox.frames import FS_CHUNK
@@ -62,39 +61,22 @@ def test_run_pumps_stdin_while_reading_output(monkeypatch):
62
61
  assert blocking.sent[-1][0] == "stdin_close"
63
62
 
64
63
 
65
- class FakeConn:
66
- """Answers one RPC with a canned frame list."""
67
-
68
- def __init__(self, frames):
69
- self._frames = list(frames)
70
- self.sent = []
71
-
72
- def __enter__(self):
73
- return self
74
-
75
- def __exit__(self, *exc):
76
- pass
77
-
78
- def send(self, op, **fields):
79
- self.sent.append((op, fields))
80
-
81
- def recv(self):
82
- return self._frames.pop(0)
83
-
84
- def recv_until(self, *terminal):
85
- while True:
86
- frame = self.recv()
87
- yield frame
88
- if frame["type"] in terminal:
89
- return
90
-
91
- def close(self):
92
- pass
64
+ @pytest.mark.parametrize(
65
+ "call",
66
+ [lambda sb: sb.run(["cat"], stdin="hi"), lambda sb: sb.exec("cat", stdin="hi")],
67
+ ids=["run", "exec"],
68
+ )
69
+ def test_a_text_stdin_is_refused_before_dialing(monkeypatch, call):
70
+ sb = sandbox_at("127.0.0.1:1", keep_alive=0)
71
+ dials = []
72
+ monkeypatch.setattr(sb, "_dial", lambda deadline=None: dials.append(deadline))
73
+ with pytest.raises(TypeError, match="stdin must be bytes"):
74
+ call(sb)
75
+ assert dials == []
93
76
 
94
77
 
95
78
  class BlockingStdinConn(FakeConn):
96
- """A guest that stops draining stdin until its output is read: send blocks
97
- past the buffer, exactly as the real socket pair does."""
79
+ """A guest that stops draining stdin until its output is read, so send blocks past the buffer."""
98
80
 
99
81
  def __init__(self, frames, buffer_frames):
100
82
  super().__init__(frames)
@@ -1,6 +1,4 @@
1
- """proxy_port end-to-end with a fake guest PortConn: catches the class of bug
2
- where proxy_port references a helper that does not exist — a static import
3
- can't see it, only running the accept loop does."""
1
+ """proxy_port end to end with a fake guest PortConn."""
4
2
 
5
3
  import socket
6
4
  import threading
@@ -7,16 +7,17 @@ from cocoonsandbox import Client, VolumeError
7
7
  from examples.volume_controller import VolumeHooks, hibernate_volume, resume_volume
8
8
 
9
9
  PATH = "/v1/sandboxes/sb_1"
10
+ HOME = {"name": "home", "mode": "rw", "attach_only": True}
10
11
  EMPTY = {"volumes_want": [], "volumes": [], "states": [], "converging": False}
11
12
  ATTACHED = {
12
- "volumes_want": [{"name": "home", "mode": "rw", "attach_only": True}],
13
- "volumes": [{"name": "home", "mode": "rw", "attach_only": True}],
13
+ "volumes_want": [HOME],
14
+ "volumes": [HOME],
14
15
  "states": [{"name": "home", "state": "attached"}],
15
16
  "converging": False,
16
17
  }
17
18
 
18
19
  REMOVE = ("patch", {"remove": ["home"]})
19
- ADD = ("patch", {"add": [{"name": "home", "mode": "rw", "attach_only": True}]})
20
+ ADD = ("patch", {"add": [HOME]})
20
21
  REMOVE_STEPS = ["close", "reserved", "unmount", REMOVE]
21
22
  ADD_STEPS = ["close", "reserved", "wake", ADD]
22
23
 
@@ -75,7 +76,7 @@ def test_controller_cycle_opens_after_verification(controller):
75
76
  resume_volume(controller.sb, "home", controller.hooks)
76
77
  assert controller.events == REMOVE_STEPS + ["hibernate"] + ADD_STEPS + ["verify", "open"]
77
78
  assert controller.gate["open"]
78
- assert controller.sb.volumes == [{"name": "home", "mode": "rw", "attach_only": True}]
79
+ assert controller.sb.volumes == [HOME]
79
80
 
80
81
 
81
82
  @pytest.mark.parametrize(
@@ -1,13 +1,4 @@
1
- """Binds the SDK's real call sites to the golden corpus: each case drives an
2
- actual Sandbox method with the fixture's own field values through a real
3
- Conn over a socketpair, then asserts the emitted frame carries exactly the
4
- fixture's fields with the same values — both directions, so a misspelled
5
- field name AND a silently dropped field fail here; the generic encode
6
- round-trip alone cannot see either.
7
-
8
- Each CASES entry is (fixture stem, scripted guest replies, invoke(sb, fixture));
9
- UNSENT lists the fields no SDK call site emits by design, which silkd defaults
10
- and the Go SDK omits too."""
1
+ """Drives each real Sandbox call site and asserts its frame carries exactly the golden fixture's fields."""
11
2
 
12
3
  import contextlib
13
4
  import json
@@ -16,7 +7,7 @@ import socket
16
7
  import threading
17
8
 
18
9
  import pytest
19
- from conftest import sandbox_at
10
+ from conftest import FakeConn, sandbox_at
20
11
 
21
12
  from cocoonsandbox import Lsp, Pty, Session
22
13
  from cocoonsandbox.conn import Conn
@@ -131,19 +122,14 @@ def test_git_branch_actions_come_from_the_corpus(monkeypatch):
131
122
  assert set(sent) == set(enums["git_branch_action"])
132
123
 
133
124
 
134
- class BranchActionConn:
125
+ class BranchActionConn(FakeConn):
135
126
  """Records the action each git_branch verb puts on the wire."""
136
127
 
137
128
  def __init__(self, sent):
129
+ super().__init__([])
138
130
  self.sent = sent
139
131
  self.action = ""
140
132
 
141
- def __enter__(self):
142
- return self
143
-
144
- def __exit__(self, *exc):
145
- pass
146
-
147
133
  def send(self, op, **fields):
148
134
  self.action = fields.get("action")
149
135
  self.sent.append(self.action)
@@ -156,13 +142,9 @@ class BranchActionConn:
156
142
  def recv_until(self, *terminal):
157
143
  yield self.recv()
158
144
 
159
- def close(self):
160
- pass
161
-
162
145
 
163
146
  def fake_sandbox(monkeypatch, replies):
164
- """A Sandbox whose _dial yields a real Conn over a socketpair; a guest
165
- thread records inbound frames and answers the scripted replies."""
147
+ """A Sandbox whose _dial yields a real Conn over a socketpair to a scripted guest thread."""
166
148
  sent = []
167
149
  client_sock, guest_sock = socket.socketpair()
168
150
 
@@ -16,55 +16,6 @@ from cocoonsandbox import sandbox as sandbox_module
16
16
  TIMEOUT = 0.2
17
17
 
18
18
 
19
- def legacy_sandbox(addr: str) -> Sandbox:
20
- return sandbox_at(addr, timeout=TIMEOUT, keep_alive=0)
21
-
22
-
23
- def serve_port_forward(server: socket.socket, quiet: float, ops: list[str]) -> None:
24
- conn, _ = server.accept()
25
- reader = accept_upgrade(conn)
26
- ops.append(json.loads(reader.readline())["op"])
27
- conn.sendall(b'{"type":"ready"}\n')
28
- time.sleep(quiet)
29
- conn.sendall(b'{"type":"data","data":"bGF0ZQ=="}\n{"type":"done"}\n')
30
- conn.close()
31
-
32
-
33
- def serve_started_then_hang(server: socket.socket, quiet: float, kills: list[dict]) -> None:
34
- conn, _ = server.accept()
35
- reader = accept_upgrade(conn)
36
- reader.readline()
37
- conn.sendall(b'{"type":"started","pid":7}\n')
38
- killer, _ = server.accept()
39
- kills.append(json.loads(accept_upgrade(killer).readline()))
40
- killer.sendall(b'{"type":"done"}\n')
41
- killer.close()
42
- time.sleep(quiet)
43
- conn.close()
44
-
45
-
46
- def serve_started_then_trickle_the_kill_reply(server: socket.socket, kills: list[dict]) -> None:
47
- conn, _ = server.accept()
48
- reader = accept_upgrade(conn)
49
- reader.readline()
50
- conn.sendall(b'{"type":"started","pid":7}\n')
51
- killer, _ = server.accept()
52
- kills.append(json.loads(accept_upgrade(killer).readline()))
53
- with contextlib.suppress(OSError):
54
- for byte in b'{"type":"done"}\n':
55
- time.sleep(0.75 * TIMEOUT)
56
- killer.sendall(bytes([byte]))
57
- killer.close()
58
- conn.close()
59
-
60
-
61
- def serve_silence(server: socket.socket) -> None:
62
- conn, _ = server.accept()
63
- conn.recv(4096)
64
- time.sleep(5 * TIMEOUT)
65
- conn.close()
66
-
67
-
68
19
  def test_port_stream_outlives_the_client_timeout():
69
20
  server = socket.create_server(("127.0.0.1", 0))
70
21
  addr = f"127.0.0.1:{server.getsockname()[1]}"
@@ -144,3 +95,52 @@ def test_dial_is_still_bounded_by_the_client_timeout():
144
95
  @pytest.mark.parametrize(("exc", "want"), [(socket.timeout(), SandboxTimeout), (ConnectionResetError(), ProtocolError)])
145
96
  def test_handshake_failures_are_typed(exc, want):
146
97
  assert isinstance(conn_module._handshake_error("agent upgrade", exc), want)
98
+
99
+
100
+ def legacy_sandbox(addr: str) -> Sandbox:
101
+ return sandbox_at(addr, timeout=TIMEOUT, keep_alive=0)
102
+
103
+
104
+ def serve_port_forward(server: socket.socket, quiet: float, ops: list[str]) -> None:
105
+ conn, _ = server.accept()
106
+ reader = accept_upgrade(conn)
107
+ ops.append(json.loads(reader.readline())["op"])
108
+ conn.sendall(b'{"type":"ready"}\n')
109
+ time.sleep(quiet)
110
+ conn.sendall(b'{"type":"data","data":"bGF0ZQ=="}\n{"type":"done"}\n')
111
+ conn.close()
112
+
113
+
114
+ def serve_started_then_hang(server: socket.socket, quiet: float, kills: list[dict]) -> None:
115
+ conn, _ = server.accept()
116
+ reader = accept_upgrade(conn)
117
+ reader.readline()
118
+ conn.sendall(b'{"type":"started","pid":7}\n')
119
+ killer, _ = server.accept()
120
+ kills.append(json.loads(accept_upgrade(killer).readline()))
121
+ killer.sendall(b'{"type":"done"}\n')
122
+ killer.close()
123
+ time.sleep(quiet)
124
+ conn.close()
125
+
126
+
127
+ def serve_started_then_trickle_the_kill_reply(server: socket.socket, kills: list[dict]) -> None:
128
+ conn, _ = server.accept()
129
+ reader = accept_upgrade(conn)
130
+ reader.readline()
131
+ conn.sendall(b'{"type":"started","pid":7}\n')
132
+ killer, _ = server.accept()
133
+ kills.append(json.loads(accept_upgrade(killer).readline()))
134
+ with contextlib.suppress(OSError):
135
+ for byte in b'{"type":"done"}\n':
136
+ time.sleep(0.75 * TIMEOUT)
137
+ killer.sendall(bytes([byte]))
138
+ killer.close()
139
+ conn.close()
140
+
141
+
142
+ def serve_silence(server: socket.socket) -> None:
143
+ conn, _ = server.accept()
144
+ conn.recv(4096)
145
+ time.sleep(5 * TIMEOUT)
146
+ conn.close()