cocoonstack-sandbox 0.1.23__tar.gz → 0.1.25__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.23 → cocoonstack_sandbox-0.1.25}/PKG-INFO +2 -2
  2. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/checkpoint.py +2 -2
  3. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/client.py +63 -39
  4. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/conn.py +26 -15
  5. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/endpoint.py +2 -2
  6. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/errors.py +18 -4
  7. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/sandbox.py +106 -33
  8. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/template.py +1 -1
  9. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonstack_sandbox.egg-info/PKG-INFO +2 -2
  10. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/pyproject.toml +2 -10
  11. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_checkpoint.py +0 -1
  12. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_client.py +26 -2
  13. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_endpoint.py +12 -10
  14. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_fault_matrix.py +98 -84
  15. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_fixtures.py +1 -4
  16. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_frames.py +0 -1
  17. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_hardening.py +1 -2
  18. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_keepalive.py +74 -2
  19. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_proc.py +1 -2
  20. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_stream.py +19 -45
  21. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_upgrade.py +7 -17
  22. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_volume_controller.py +3 -2
  23. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_volumes.py +14 -25
  24. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_wire_binding.py +1 -8
  25. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/LICENSE +0 -0
  26. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/README.md +0 -0
  27. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/__init__.py +0 -0
  28. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/frames.py +0 -0
  29. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/py.typed +0 -0
  30. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonsandbox/volumes.py +0 -0
  31. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonstack_sandbox.egg-info/SOURCES.txt +0 -0
  32. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonstack_sandbox.egg-info/dependency_links.txt +0 -0
  33. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/cocoonstack_sandbox.egg-info/top_level.txt +0 -0
  34. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/setup.cfg +0 -0
  35. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_packaging.py +0 -0
  36. {cocoonstack_sandbox-0.1.23 → cocoonstack_sandbox-0.1.25}/tests/test_proxy.py +0 -0
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.23
3
+ Version: 0.1.25
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
- Requires-Python: >=3.9
6
+ Requires-Python: >=3.10
7
7
  Description-Content-Type: text/markdown
8
8
  License-File: LICENSE
9
9
  Dynamic: license-file
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  from typing import TYPE_CHECKING, Any
6
6
 
7
- from .errors import require_field
7
+ from .errors import _require_field
8
8
 
9
9
  if TYPE_CHECKING:
10
10
  from .client import Client
@@ -17,7 +17,7 @@ class Checkpoint:
17
17
  def __init__(self, client: Client, addr: str, rec: dict[str, Any]) -> None:
18
18
  self._client = client
19
19
  self._addr = addr
20
- self.id = require_field(rec, "id", "checkpoint")
20
+ self.id = _require_field(rec, "id", "checkpoint")
21
21
  self.name = rec.get("name", "")
22
22
  self.sandbox_id = rec.get("sandbox_id", "")
23
23
  self.created_at = rec.get("created_at", "")
@@ -13,20 +13,20 @@ from collections.abc import Callable, Iterable, Sequence
13
13
  from typing import Any, TypeVar, cast
14
14
 
15
15
  from .checkpoint import Checkpoint
16
- from .conn import Conn, dial_agent, is_quiet, remaining_timeout
16
+ from .conn import Conn, _Closeable, dial_agent, is_quiet, remaining_timeout
17
17
  from .endpoint import _endpoint_url
18
- from .errors import APIError, SandboxTimeout, _error_message, require_field
18
+ from .errors import APIError, SandboxTimeout, _DialError, _error_message, _require_field
19
19
  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")
23
+ _T = TypeVar("_T")
24
24
 
25
25
  _PEERS_TIMEOUT = 5.0
26
26
  _IDLE_CONNS = 8
27
27
 
28
28
 
29
- class Client:
29
+ class Client(_Closeable):
30
30
  """Talks to one sandboxd node (and, transparently, its cluster)."""
31
31
 
32
32
  def __init__(
@@ -38,11 +38,11 @@ class Client:
38
38
  ssl_context: ssl.SSLContext | None = None,
39
39
  keep_alive: float = 30.0,
40
40
  ) -> None:
41
- """keep_alive parks idle control and relay connections, which hold the sandbox's idle clock; 0 dials per call.
41
+ """keep_alive parks idle connections, 0 dials per call; a parked relay one holds the sandbox's idle clock.
42
42
 
43
43
  ssl_context is set to offer ALPN http/1.1, which the relay upgrade needs; pass a dedicated context.
44
44
  """
45
- endpoint = _endpoint_url(addr.split(",")[0].strip())
45
+ endpoint = _endpoint_url(addr.strip())
46
46
  self.addr = endpoint.geturl().removeprefix("http://")
47
47
  self._scheme = endpoint.scheme
48
48
  self._ssl_context = ssl_context
@@ -96,11 +96,12 @@ class Client:
96
96
  )
97
97
  return Sandbox(client=self, id=id, token=token, owner=reply.get("owner_addr") or addr)
98
98
 
99
- addrs = [self.addr, *self._peers()]
99
+ peers, peers_err = self._peers()
100
100
  try:
101
- return _scatter(addrs, probe)
101
+ return _scatter([self.addr, *peers], probe)
102
102
  except APIError:
103
- raise APIError("lookup", 404, f"no owner found for {id}") from None
103
+ reason = f"no owner found for {id}" if peers_err is None else f"no owner found for {id}; {peers_err}"
104
+ raise APIError("lookup", 404, reason) from None
104
105
 
105
106
  def attach(self, owner_addr: str, id: str, token: str) -> Sandbox:
106
107
  """Binds a handle to a known owner without a lookup."""
@@ -112,12 +113,20 @@ class Client:
112
113
  return [dict(sb) for sb in reply.get("sandboxes") or []]
113
114
 
114
115
  def drain(self) -> dict[str, Any]:
115
- """Cordons the node (root token): new claims are refused, live ones run to their leases."""
116
+ """Drains the node (root token): new claims are refused, live ones run to their leases."""
116
117
  return self._request(self.addr, "POST", "/v1/drain", None, "drain")
117
118
 
118
- def uncordon(self) -> dict[str, Any]:
119
+ def undrain(self) -> dict[str, Any]:
119
120
  """Lifts a drain on the node (root token)."""
120
- return self._request(self.addr, "DELETE", "/v1/drain", None, "uncordon")
121
+ return self._request(self.addr, "DELETE", "/v1/drain", None, "undrain")
122
+
123
+ def cordon(self) -> dict[str, Any]:
124
+ """Refuses new claims across restarts (root token); live claims and moves in stay admitted."""
125
+ return self._request(self.addr, "POST", "/v1/cordon", None, "cordon")
126
+
127
+ def uncordon(self) -> dict[str, Any]:
128
+ """Lifts a cordon on the node (root token); a drain stays."""
129
+ return self._request(self.addr, "DELETE", "/v1/cordon", None, "uncordon")
121
130
 
122
131
  def checkpoint(self, id: str) -> Checkpoint:
123
132
  """Binds a checkpoint handle to the entry node without a lookup."""
@@ -137,6 +146,14 @@ class Client:
137
146
  """The node's pool/claim counters, as served by GET /v1/info."""
138
147
  return self._request(self.addr, "GET", "/v1/info", None, "info")
139
148
 
149
+ def close(self) -> None:
150
+ """Closes the parked control connections; a later call dials afresh."""
151
+ with self._idle_lock:
152
+ while self._idle:
153
+ _, idle = self._idle.popitem()
154
+ for conn, _ in idle:
155
+ conn.close()
156
+
140
157
  def _claim_from(
141
158
  self,
142
159
  addr: str,
@@ -146,7 +163,7 @@ class Client:
146
163
  *,
147
164
  deadline: float | None = None,
148
165
  ) -> Sandbox:
149
- reply = self._post_json(addr, path, claim, verb, deadline=deadline)
166
+ reply = self._request(addr, "POST", path, claim, verb, deadline=deadline)
150
167
  redirect = reply.get("redirect") or []
151
168
  if not redirect:
152
169
  return self._handle_from(addr, reply, verb)
@@ -155,27 +172,25 @@ class Client:
155
172
  claim["require_promoted"] = True
156
173
 
157
174
  def post(peer: str) -> dict[str, Any]:
158
- return self._post_json(peer, path, claim, verb, deadline=deadline)
175
+ return self._request(peer, "POST", path, claim, verb, deadline=deadline)
159
176
 
160
177
  owner, reply = _redirect_fallback(addr, redirect, post, verb)
161
178
  return self._handle_from(owner, reply, verb)
162
179
 
163
- def _peers(self) -> list[str]:
180
+ def _peers(self) -> tuple[list[str], APIError | None]:
164
181
  try:
165
- return (
166
- self._request(
167
- self.addr, "GET", "/v1/peers", None, "peers", timeout=min(_PEERS_TIMEOUT, self.timeout)
168
- ).get("peers")
169
- or []
182
+ reply = self._request(
183
+ self.addr, "GET", "/v1/peers", None, "peers", timeout=min(_PEERS_TIMEOUT, self.timeout)
170
184
  )
171
- except APIError:
172
- return []
185
+ except APIError as exc:
186
+ return [], exc
187
+ return reply.get("peers") or [], None
173
188
 
174
189
  def _handle_from(self, dialed: str, reply: dict[str, Any], verb: str = "claim") -> Sandbox:
175
190
  return Sandbox(
176
191
  client=self,
177
- id=require_field(reply, "id", verb),
178
- token=require_field(reply, "token", verb),
192
+ id=_require_field(reply, "id", verb),
193
+ token=_require_field(reply, "token", verb),
179
194
  owner=reply.get("owner_addr") or dialed,
180
195
  deadline=reply.get("deadline", ""),
181
196
  from_checkpoint=reply.get("from_checkpoint", ""),
@@ -183,11 +198,6 @@ class Client:
183
198
  volumes=reply.get("volumes") or [],
184
199
  )
185
200
 
186
- def _post_json(
187
- self, addr: str, path: str, body: dict[str, Any], verb: str, *, deadline: float | None = None
188
- ) -> dict[str, Any]:
189
- return self._request(addr, "POST", path, body, verb, deadline=deadline)
190
-
191
201
  def _request(
192
202
  self,
193
203
  addr: str,
@@ -211,7 +221,7 @@ class Client:
211
221
  except (OSError, http.client.HTTPException) as exc:
212
222
  if deadline is not None and time.monotonic() >= deadline:
213
223
  raise SandboxTimeout(f"{verb} timed out") from None
214
- raise APIError(verb, 0, str(exc)) from None
224
+ raise APIError(verb, 0, str(exc)) from exc
215
225
  if status >= 400:
216
226
  try:
217
227
  reply = json.loads(raw)
@@ -228,13 +238,21 @@ class Client:
228
238
  def _dial(self, addr: str, sandbox_id: str, token: str, deadline: float | None = None) -> Conn:
229
239
  origin = addr if "://" in addr else f"{self._scheme}://{addr}"
230
240
  context = self._tls() if origin.startswith("https://") else None
231
- return dial_agent(origin, sandbox_id, token, self.timeout, deadline, ssl_context=context)
241
+ return dial_agent(
242
+ origin, sandbox_id, token, self.timeout, deadline, ssl_context=context, tag=(sandbox_id, addr)
243
+ )
232
244
 
233
245
  def _roundtrip(
234
246
  self, url: urllib.parse.SplitResult, method: str, data: bytes | None, headers: dict[str, str], timeout: float
235
247
  ) -> tuple[int, bytes]:
236
248
  key = (url.scheme, url.netloc)
237
249
  conn = self._take(key, timeout)
250
+ if conn.sock is None:
251
+ try:
252
+ conn.connect()
253
+ except OSError as exc:
254
+ conn.close()
255
+ raise _DialError(str(exc)) from exc
238
256
  status = 0
239
257
  try:
240
258
  conn.request(method, url.path + (f"?{url.query}" if url.query else ""), body=data, headers=headers)
@@ -283,8 +301,8 @@ def _retry_miss(exc: APIError) -> bool:
283
301
 
284
302
 
285
303
  def _try_each(
286
- candidates: Iterable[str], call: Callable[[str], T], retry: Callable[[APIError], bool] = _retry_miss
287
- ) -> T:
304
+ candidates: Iterable[str], call: Callable[[str], _T], retry: Callable[[APIError], bool] = _retry_miss
305
+ ) -> _T:
288
306
  last_error = None
289
307
  for addr in candidates:
290
308
  try:
@@ -297,7 +315,13 @@ def _try_each(
297
315
 
298
316
 
299
317
  def _retry_transient(exc: APIError) -> bool:
300
- return exc.status in (0, 401, 404, 429, 503, 500, 502, 504)
318
+ return exc.status in (0, 401, 404, 429, 500, 503)
319
+
320
+
321
+ def _claim_refused(exc: APIError) -> bool:
322
+ if exc.status:
323
+ return exc.status not in (502, 504)
324
+ return exc.__cause__ is None or isinstance(exc.__cause__, _DialError)
301
325
 
302
326
 
303
327
  def _redirect_fallback(
@@ -310,9 +334,9 @@ def _redirect_fallback(
310
334
  return addr, reply
311
335
 
312
336
  try:
313
- return _try_each(candidates, attempt, retry=lambda _: True)
337
+ return _try_each(candidates, attempt, retry=_claim_refused)
314
338
  except APIError as exc:
315
- if not _retry_transient(exc):
339
+ if not (_claim_refused(exc) and _retry_transient(exc)):
316
340
  raise
317
341
  try:
318
342
  return attempt(origin)
@@ -321,8 +345,8 @@ def _redirect_fallback(
321
345
  raise APIError(verb, origin_exc.status, combined) from origin_exc
322
346
 
323
347
 
324
- def _scatter(addrs: Sequence[str], probe: Callable[[str], T]) -> T:
325
- results: queue.Queue[tuple[T | None, Exception | None]] = queue.Queue(maxsize=len(addrs))
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))
326
350
 
327
351
  def run(addr: str) -> None:
328
352
  try:
@@ -336,6 +360,6 @@ def _scatter(addrs: Sequence[str], probe: Callable[[str], T]) -> T:
336
360
  for _ in addrs:
337
361
  value, error = results.get()
338
362
  if error is None:
339
- return cast(T, value)
363
+ return cast(_T, value)
340
364
  last_error = error
341
365
  raise cast(Exception, last_error)
@@ -12,10 +12,10 @@ import urllib.parse
12
12
  from collections.abc import Callable, Iterator
13
13
  from typing import Any, BinaryIO, Protocol, TypeVar, cast
14
14
 
15
- from .errors import APIError, ProtocolError, SandboxError, SandboxTimeout, SilkdError, _error_message
15
+ from .errors import APIError, ProtocolError, SandboxError, SandboxTimeout, SilkdError, _error_message, _mark_gone
16
16
  from .frames import MAX_FRAME, decode_response, encode_request
17
17
 
18
- KEEP_ALIVE_CONNS = 8
18
+ _KEEP_ALIVE_CONNS = 8
19
19
  _FD_SETSIZE = 1024
20
20
  _READ_BUFFER = 64 * 1024
21
21
  _TCP_KEEPALIVE = {"TCP_KEEPIDLE": 15, "TCP_KEEPALIVE": 15, "TCP_KEEPINTVL": 15, "TCP_KEEPCNT": 9}
@@ -37,12 +37,18 @@ class Conn(_Closeable):
37
37
  """A frame stream to one sandbox's silkd; a plain-HTTP upgrade rides the first send, its 101 the first recv."""
38
38
 
39
39
  def __init__(
40
- self, sock: socket.socket, reader: BinaryIO, request: bytes = b"", upgrade_timeout: float | None = None
40
+ self,
41
+ sock: socket.socket,
42
+ reader: BinaryIO,
43
+ request: bytes = b"",
44
+ upgrade_timeout: float | None = None,
45
+ tag: tuple[str, str] = ("", ""),
41
46
  ) -> None:
42
47
  self._sock = sock
43
48
  self._reader = reader
44
49
  self._request = request
45
50
  self._upgrade_timeout = upgrade_timeout
51
+ self._tag = tag
46
52
 
47
53
  def send(self, op: str, **fields: object) -> None:
48
54
  frame = encode_request(op, **fields)
@@ -107,7 +113,9 @@ class Conn(_Closeable):
107
113
  deadline = time.monotonic() + limit
108
114
  try:
109
115
  _read_upgrade(
110
- self._reader, lambda: self._sock.settimeout(remaining_timeout(limit, deadline, "agent upgrade"))
116
+ self._reader,
117
+ lambda: self._sock.settimeout(remaining_timeout(limit, deadline, "agent upgrade")),
118
+ self._tag,
111
119
  )
112
120
  self._sock.settimeout(caller)
113
121
  except Exception as exc:
@@ -138,7 +146,7 @@ class ConnPool:
138
146
 
139
147
  def park(self, conn: Conn) -> None:
140
148
  with self._lock:
141
- if self._idle > 0 and len(self._parked) < KEEP_ALIVE_CONNS:
149
+ if self._idle > 0 and len(self._parked) < _KEEP_ALIVE_CONNS:
142
150
  self._parked.append((time.monotonic() + self._idle, conn))
143
151
  if self._sweep is None:
144
152
  self._arm(self._idle)
@@ -179,6 +187,7 @@ def dial_agent(
179
187
  deadline: float | None = None,
180
188
  *,
181
189
  ssl_context: ssl.SSLContext | None = None,
190
+ tag: tuple[str, str] = ("", ""),
182
191
  ) -> Conn:
183
192
  """Opens one TCP/HTTP Upgrade relay within timeout and the optional deadline."""
184
193
  budget = time.monotonic() + timeout
@@ -192,12 +201,8 @@ def dial_agent(
192
201
  try:
193
202
  sock = socket.create_connection((host, port), timeout=remaining_timeout(timeout, deadline))
194
203
  except OSError as exc:
195
- raise _handshake_error(f"dial {addr}", exc) from exc
196
- sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
197
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
198
- for opt, setting in _TCP_KEEPALIVE.items():
199
- if hasattr(socket, opt):
200
- sock.setsockopt(socket.IPPROTO_TCP, getattr(socket, opt), setting)
204
+ err = _handshake_error(f"dial {addr}", exc)
205
+ raise (_mark_gone(err, tag) if isinstance(exc, ConnectionRefusedError) else err) from exc
201
206
  request = (
202
207
  f"GET /v1/sandboxes/{sandbox_id}/agent HTTP/1.1\r\n"
203
208
  f"Host: {endpoint.netloc}\r\n"
@@ -208,9 +213,14 @@ def dial_agent(
208
213
  ).encode()
209
214
  reader = None
210
215
  try:
216
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
217
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
218
+ for opt, setting in _TCP_KEEPALIVE.items():
219
+ if hasattr(socket, opt):
220
+ sock.setsockopt(socket.IPPROTO_TCP, getattr(socket, opt), setting)
211
221
  if endpoint.scheme != "https":
212
222
  sock.settimeout(None)
213
- return Conn(sock, _buffered_reader(sock), request, timeout)
223
+ return Conn(sock, _buffered_reader(sock), request, timeout, tag)
214
224
  context = ssl_context or ssl.create_default_context()
215
225
  sock = context.wrap_socket(sock, server_hostname=host, do_handshake_on_connect=False)
216
226
  sock.settimeout(remaining_timeout(timeout, deadline))
@@ -222,7 +232,7 @@ def dial_agent(
222
232
  sock.settimeout(remaining_timeout(timeout, deadline))
223
233
  sock.sendall(request)
224
234
  reader = _buffered_reader(sock)
225
- _read_upgrade(reader, lambda: sock.settimeout(remaining_timeout(timeout, deadline)))
235
+ _read_upgrade(reader, lambda: sock.settimeout(remaining_timeout(timeout, deadline)), tag)
226
236
  remaining_timeout(timeout, deadline)
227
237
  sock.settimeout(None)
228
238
  return Conn(sock, reader)
@@ -269,7 +279,7 @@ def _handshake_error(what: str, exc: OSError) -> SandboxError:
269
279
  return ProtocolError(f"{what}: {exc}")
270
280
 
271
281
 
272
- def _read_upgrade(reader: BinaryIO, arm: Callable[[], None]) -> None:
282
+ def _read_upgrade(reader: BinaryIO, arm: Callable[[], None], tag: tuple[str, str]) -> None:
273
283
  arm()
274
284
  status = reader.readline(1024).decode(errors="replace")
275
285
  if not status:
@@ -293,4 +303,5 @@ def _read_upgrade(reader: BinaryIO, arm: Callable[[], None]) -> None:
293
303
  if code != 101:
294
304
  arm()
295
305
  body = reader.read(min(body_len, MAX_FRAME)) if body_len else b""
296
- raise APIError("agent upgrade", code, _error_message(body) or status.strip())
306
+ err = APIError("agent upgrade", code, _error_message(body) or status.strip())
307
+ raise _mark_gone(err, tag) if code == 404 else err
@@ -5,11 +5,11 @@ from __future__ import annotations
5
5
  import urllib.parse
6
6
 
7
7
 
8
- def _endpoint_url(addr: str, scheme: str = "http") -> urllib.parse.SplitResult:
8
+ def _endpoint_url(addr: str) -> urllib.parse.SplitResult:
9
9
  if any(ord(c) <= 32 or ord(c) == 127 for c in addr):
10
10
  raise ValueError("sandboxd endpoint contains whitespace or a control character")
11
11
  if "://" not in addr:
12
- addr = f"{scheme}://{addr}"
12
+ addr = f"http://{addr}"
13
13
  endpoint = urllib.parse.urlsplit(addr)
14
14
  if (
15
15
  endpoint.scheme not in ("http", "https")
@@ -3,15 +3,19 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
- from typing import TYPE_CHECKING, Any, cast
6
+ from typing import TYPE_CHECKING, Any, TypeVar, cast
7
7
 
8
8
  if TYPE_CHECKING:
9
9
  from .volumes import SandboxVolumesResponse
10
10
 
11
+ _E = TypeVar("_E", bound="SandboxError")
12
+
11
13
 
12
14
  class SandboxError(Exception):
13
15
  """Base class for all SDK errors."""
14
16
 
17
+ _owner_gone: tuple[str, str] | None = None
18
+
15
19
 
16
20
  class SandboxTimeout(SandboxError, TimeoutError):
17
21
  """A caller's timeout or deadline expired before the call finished."""
@@ -49,7 +53,8 @@ class ExitError(SandboxError):
49
53
  """A command exited non-zero; carries the code, stderr, and the stdout produced before it failed."""
50
54
 
51
55
  def __init__(self, code: int, stderr: str, stdout: str = "") -> None:
52
- super().__init__(f"exit status {code}: {stderr.strip()}")
56
+ detail = stderr.strip()
57
+ super().__init__(f"exit status {code}: {detail}" if detail else f"exit status {code}")
53
58
  self.code = code
54
59
  self.stderr = stderr
55
60
  self.stdout = stdout
@@ -59,8 +64,11 @@ class ProtocolError(SandboxError):
59
64
  """The peer broke the frame protocol (unexpected frame, oversized line)."""
60
65
 
61
66
 
62
- def require_field(reply: dict[str, Any], key: str, verb: str) -> Any:
63
- """The named member of a control-plane reply, or an APIError naming the verb that got a truncated one."""
67
+ class _DialError(OSError):
68
+ pass
69
+
70
+
71
+ def _require_field(reply: dict[str, Any], key: str, verb: str) -> Any:
64
72
  if key not in reply:
65
73
  raise APIError(verb, 0, f"reply without {key}")
66
74
  return reply[key]
@@ -71,3 +79,9 @@ def _error_message(raw: bytes) -> str:
71
79
  return cast(str, json.loads(raw)["error"])
72
80
  except (ValueError, KeyError, TypeError):
73
81
  return raw.decode(errors="replace").strip()
82
+
83
+
84
+ def _mark_gone(exc: _E, tag: tuple[str, str]) -> _E:
85
+ """Tags an owner's 404 or refused dial with its (sandbox id, owner address)."""
86
+ exc._owner_gone = tag
87
+ return exc