devzero-sandbox 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,634 @@
1
+ """Sandboxes: the control-plane client and one sandbox's handle (ADR-007-W13).
2
+
3
+ Two endpoints, two credentials (``sandbox-sdks/CLAUDE.md``):
4
+
5
+ - **Control plane**: DevZero's ``SandboxService`` (Connect, generated from
6
+ ``dakr/proto/sandbox/v1``), with a DevZero credential: a ``dzu-`` personal
7
+ access token or a ``dzs-`` team service-account token, from ``token=`` or
8
+ ``DEVZERO_TOKEN``; the API host from ``api_url=`` or ``DEVZERO_DAKR_URL``
9
+ (the same variables as the ``dz`` CLI).
10
+ - **Data plane**: the sandbox's gateway URL (``connect.url``) with the sandbox
11
+ JWT ``CreateSandbox`` returned, or, inside the cluster, the gateway's
12
+ ``.svc`` name with the pod's projected ServiceAccount token
13
+ (:meth:`Sandbox.in_cluster`).
14
+
15
+ ``client.sandboxes.create(policy)`` waits for ``ready`` by default: it calls
16
+ ``CreateSandbox`` with ``wait_ready`` (the server waits up to its own bound)
17
+ and, if the answer is still ``pending``, follows ``WatchSandbox`` until
18
+ ``ready`` or ``timeout_s``. Every create carries an idempotency key, so a
19
+ create whose answer was lost is asked again with the same key, which returns
20
+ the same sandbox with a fresh token (ADR-003 §API contract).
21
+
22
+ Transport selection: Phase 1 data-plane transports are REST, SSE and
23
+ WebSocket. Native gRPC (Phase 2, ADR-007-W10) is used only when
24
+ ``ListSandboxPolicies`` advertises it, and today's ``SandboxPolicyInfo``
25
+ advertises no such field, so the SDK always uses SSE/WebSocket.
26
+
27
+ Lifecycle (ADR-010-W11): ``sandbox.extend(ttl)`` moves the shutdown time to
28
+ ``now + ttl`` through ``ExtendSandbox`` and never touches a token; DevZero
29
+ applies the rules (an extension of at least 60 s and at most ``maxTTL``,
30
+ clamped to creation + ``maxTTL``, ``max_ttl_reached`` at the ceiling). A
31
+ sandbox the gateway calls gone raises
32
+ :class:`~devzero_sandbox.errors.SandboxGone` with the reason DevZero recorded
33
+ (``Expired``, ``Idle``, ``Deleted``, ``PolicyDraining``, ``CrashLoop``).
34
+ Idle is the gateway's to observe (ADR-010 rejects an SDK heartbeat), so the
35
+ SDK sends nothing to keep a sandbox alive.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import os
41
+ import time
42
+ import uuid
43
+ from collections.abc import Callable, Iterator, Mapping, Sequence
44
+ from datetime import UTC, datetime, timedelta
45
+ from types import TracebackType
46
+ from typing import Any, Self
47
+
48
+ import httpx
49
+ from google.protobuf.duration_pb2 import Duration
50
+ from google.protobuf.timestamp_pb2 import Timestamp
51
+
52
+ from devzero_sandbox import errors
53
+ from devzero_sandbox._proto.sandbox.v1 import service_pb2 as pb
54
+ from devzero_sandbox._proto.sandbox.v1.service_connect import SandboxServiceClient
55
+ from devzero_sandbox.auth import SandboxToken, TokenCredentials
56
+ from devzero_sandbox.commands import WORKSPACE, Commands, Process
57
+ from devzero_sandbox.connect import ConnectClient
58
+ from devzero_sandbox.files import Files
59
+ from devzero_sandbox.incluster import (
60
+ IN_CLUSTER_CA_PATH,
61
+ IN_CLUSTER_GATEWAY_URL,
62
+ IN_CLUSTER_TOKEN_PATH,
63
+ )
64
+ from devzero_sandbox.redaction import get_logger
65
+ from devzero_sandbox.terminal import Terminal
66
+ from devzero_sandbox.transport import GatewayTransport
67
+
68
+ log = get_logger(__name__)
69
+
70
+ DEFAULT_API_URL = "https://dakr.devzero.io"
71
+ ENV_TOKEN = "DEVZERO_TOKEN"
72
+ ENV_API_URL = "DEVZERO_DAKR_URL"
73
+ #: The server bounds wait_ready at the cluster's pending ceiling (900 s by default).
74
+ _MAX_WAIT_READY_S = 900
75
+
76
+ _TERMINAL_PHASES = {"failed", "rejected", "terminating", "deleted"}
77
+
78
+
79
+ def phase_name(phase: int) -> str:
80
+ """``PHASE_READY`` → ``"ready"`` (the one status enum, ADR-003)."""
81
+ return pb.Phase.Name(phase).removeprefix("PHASE_").lower()
82
+
83
+
84
+ class Client:
85
+ """DevZero's control plane for sandboxes; ``client.sandboxes`` creates and finds them."""
86
+
87
+ def __init__(
88
+ self,
89
+ token: str | None = None,
90
+ *,
91
+ api_url: str | None = None,
92
+ timeout: float = 60.0,
93
+ http_transport: httpx.BaseTransport | None = None,
94
+ gateway_options: Mapping[str, Any] | None = None,
95
+ clock: Callable[[], float] = time.monotonic,
96
+ sleep: Callable[[float], None] = time.sleep,
97
+ wall_clock: Callable[[], float] = time.time,
98
+ ) -> None:
99
+ token = token if token is not None else os.environ.get(ENV_TOKEN) or None
100
+ self.api_url = api_url or os.environ.get(ENV_API_URL) or DEFAULT_API_URL
101
+ self._clock, self._sleep = clock, sleep
102
+ # Seconds since the epoch: ``extend(ttl)`` asks for now + ttl.
103
+ self._wall_clock = wall_clock
104
+ self._connect = ConnectClient(
105
+ self.api_url,
106
+ token,
107
+ timeout=timeout,
108
+ http_transport=http_transport,
109
+ clock=clock,
110
+ sleep=sleep,
111
+ )
112
+ #: The generated SandboxService stub, for RPCs this wrapper does not cover.
113
+ self.api = SandboxServiceClient(self._connect)
114
+ # Extra keyword arguments for every GatewayTransport this client builds
115
+ # (a BYO gateway's ``ca_bundle``; tests pass an in-process transport).
116
+ self.gateway_options = dict(gateway_options or {})
117
+ self.sandboxes = Sandboxes(self)
118
+
119
+ def policies(self, cluster_id: str = "") -> list[pb.SandboxPolicyInfo]:
120
+ """Every (cluster, policy) the caller may use, with limits and the connect template."""
121
+ out: list[pb.SandboxPolicyInfo] = []
122
+ token = ""
123
+ while True:
124
+ resp = self.api.list_sandbox_policies(
125
+ pb.ListSandboxPoliciesRequest(cluster_id=cluster_id, page_token=token),
126
+ retry=True,
127
+ )
128
+ out.extend(resp.policies)
129
+ token = resp.next_page_token
130
+ if not token:
131
+ return out
132
+
133
+ def close(self) -> None:
134
+ self._connect.close()
135
+
136
+ def __enter__(self) -> Self:
137
+ return self
138
+
139
+ def __exit__(
140
+ self,
141
+ exc_type: type[BaseException] | None,
142
+ exc: BaseException | None,
143
+ tb: TracebackType | None,
144
+ ) -> None:
145
+ self.close()
146
+
147
+ def __repr__(self) -> str:
148
+ return f"Client({self.api_url!r})"
149
+
150
+
151
+ class Sandboxes:
152
+ """``client.sandboxes``: create, get and list."""
153
+
154
+ def __init__(self, client: Client) -> None:
155
+ self._client = client
156
+
157
+ def create(
158
+ self,
159
+ policy: str,
160
+ *,
161
+ cluster_id: str = "",
162
+ wait: bool = True,
163
+ timeout_s: float = 300,
164
+ ttl_s: int | None = None,
165
+ image: str = "",
166
+ resources: Mapping[str, str] | None = None,
167
+ labels: Mapping[str, str] | None = None,
168
+ idempotency_key: str | None = None,
169
+ ) -> Sandbox:
170
+ """Create a sandbox from ``policy`` and, with ``wait``, return once it is ready.
171
+
172
+ Raises :class:`~devzero_sandbox.errors.SandboxWaitTimeout` if it is not
173
+ ready within ``timeout_s`` (the sandbox stays; ``sandbox.wait()``
174
+ continues), :class:`~devzero_sandbox.errors.RejectedInCluster` or
175
+ :class:`~devzero_sandbox.errors.SandboxFailed` if it never will be.
176
+ """
177
+ api = self._client.api
178
+ clock = self._client._clock
179
+ deadline = clock() + timeout_s
180
+ req = pb.CreateSandboxRequest(
181
+ policy=policy,
182
+ cluster_id=cluster_id,
183
+ image=image,
184
+ labels=dict(labels or {}),
185
+ wait_ready=wait,
186
+ idempotency_key=idempotency_key or f"sdk-{uuid.uuid4()}",
187
+ )
188
+ if ttl_s is not None:
189
+ req.ttl.CopyFrom(Duration(seconds=int(ttl_s)))
190
+ if resources:
191
+ req.resources.CopyFrom(pb.Resources(**dict(resources)))
192
+ if wait:
193
+ req.wait_timeout.CopyFrom(
194
+ Duration(seconds=max(1, min(int(timeout_s), _MAX_WAIT_READY_S)))
195
+ )
196
+ try:
197
+ resp = api.create_sandbox(
198
+ req, timeout_s=timeout_s if wait else None, retry=True
199
+ )
200
+ except errors.ControlPlaneError as e:
201
+ if e.connect_code != "deadline_exceeded":
202
+ raise
203
+ # Our deadline beat the server's wait; creation continues. The same
204
+ # key returns the same sandbox (with a fresh token) without waiting.
205
+ req.wait_ready = False
206
+ req.ClearField("wait_timeout")
207
+ resp = api.create_sandbox(req, retry=True)
208
+ sbx = Sandbox._from_create(self._client, resp)
209
+ if wait:
210
+ sbx.wait(timeout_s=max(0.0, deadline - clock()))
211
+ return sbx
212
+
213
+ def get(self, sandbox_id: str) -> Sandbox:
214
+ """A sandbox by id. It carries no token (tokens come only from create and
215
+ ``sandbox.tokens.mint``), so mint one before using its data plane."""
216
+ resp = self._client.api.get_sandbox(
217
+ pb.GetSandboxRequest(id=sandbox_id), retry=True
218
+ )
219
+ return Sandbox(resp.sandbox, client=self._client)
220
+
221
+ def connect(self, sandbox_id: str, token: str) -> Sandbox:
222
+ """A sandbox by id, with a sandbox token the caller already holds."""
223
+ resp = self._client.api.get_sandbox(
224
+ pb.GetSandboxRequest(id=sandbox_id), retry=True
225
+ )
226
+ return Sandbox(
227
+ resp.sandbox, client=self._client, credentials=TokenCredentials(token)
228
+ )
229
+
230
+ def list(
231
+ self,
232
+ *,
233
+ policy: str = "",
234
+ cluster_id: str = "",
235
+ labels: Mapping[str, str] | None = None,
236
+ ) -> Iterator[Sandbox]:
237
+ """Every sandbox the caller can see, filtered, page by page."""
238
+ token = ""
239
+ while True:
240
+ resp = self._client.api.list_sandboxes(
241
+ pb.ListSandboxesRequest(
242
+ policy=policy,
243
+ cluster_id=cluster_id,
244
+ labels=dict(labels or {}),
245
+ page_token=token,
246
+ ),
247
+ retry=True,
248
+ )
249
+ for s in resp.sandboxes:
250
+ yield Sandbox(s, client=self._client)
251
+ token = resp.next_page_token
252
+ if not token:
253
+ return
254
+
255
+
256
+ class Tokens:
257
+ """``sandbox.tokens``: mint more sandbox tokens, revoke one (ADR-005)."""
258
+
259
+ def __init__(self, sandbox: Sandbox) -> None:
260
+ self._s = sandbox
261
+
262
+ def mint(
263
+ self, scope: Sequence[str] = (), *, ttl_s: int | None = None
264
+ ) -> SandboxToken:
265
+ """Mint a token (``scope``: a subset of exec, files, terminal, watch, ports;
266
+ empty is all) and hold it; the SDK sends the narrowest held token per request."""
267
+ req = pb.CreateSandboxTokenRequest(
268
+ sandbox_id=self._s.id,
269
+ scope=list(scope),
270
+ idempotency_key=f"sdk-{uuid.uuid4()}",
271
+ )
272
+ if ttl_s is not None:
273
+ req.ttl.CopyFrom(Duration(seconds=int(ttl_s)))
274
+ resp = self._s._api().create_sandbox_token(req, retry=True)
275
+ tok = SandboxToken(
276
+ resp.token,
277
+ jti=resp.jti or None,
278
+ scopes=list(scope) or None,
279
+ expires_at=float(resp.expires_at.seconds)
280
+ if resp.HasField("expires_at")
281
+ else None,
282
+ )
283
+ self._s._token_credentials().add(tok)
284
+ return tok
285
+
286
+ def revoke(self, jti: str) -> str:
287
+ """Revoke a token by ``jti`` and stop using it; returns ``pending`` or ``applied``."""
288
+ resp = self._s._api().revoke_sandbox_token(
289
+ pb.RevokeSandboxTokenRequest(
290
+ sandbox_id=self._s.id, jti=jti, idempotency_key=f"sdk-{uuid.uuid4()}"
291
+ ),
292
+ retry=True,
293
+ )
294
+ creds = self._s._credentials
295
+ if isinstance(creds, TokenCredentials):
296
+ creds.remove(jti)
297
+ return (
298
+ pb.RevocationStatus.Name(resp.status)
299
+ .removeprefix("REVOCATION_STATUS_")
300
+ .lower()
301
+ )
302
+
303
+
304
+ class Sandbox:
305
+ """One sandbox: ``commands``, ``files``, ``terminal()``, ``kill(pid)``, ``delete()``."""
306
+
307
+ def __init__(
308
+ self,
309
+ info: pb.Sandbox,
310
+ *,
311
+ client: Client | None = None,
312
+ credentials: TokenCredentials | None = None,
313
+ transport: GatewayTransport | None = None,
314
+ workspace: str = WORKSPACE,
315
+ ) -> None:
316
+ self.info = info
317
+ self._client = client
318
+ self._credentials: TokenCredentials | None = credentials
319
+ self._transport = transport
320
+ self.workspace = workspace
321
+ self.tokens = Tokens(self)
322
+ self._commands: Commands | None = None
323
+ self._files: Files | None = None
324
+
325
+ # --- construction ------------------------------------------------------------
326
+
327
+ @classmethod
328
+ def _from_create(cls, client: Client, resp: pb.CreateSandboxResponse) -> Sandbox:
329
+ creds = TokenCredentials()
330
+ if resp.token:
331
+ creds.add(
332
+ SandboxToken(
333
+ resp.token,
334
+ expires_at=float(resp.token_expires_at.seconds)
335
+ if resp.HasField("token_expires_at")
336
+ else None,
337
+ )
338
+ )
339
+ sbx = cls(resp.sandbox, client=client, credentials=creds)
340
+ if sbx.status == "ready":
341
+ sbx.transport.mark_ready()
342
+ return sbx
343
+
344
+ @classmethod
345
+ def in_cluster(
346
+ cls,
347
+ policy: str,
348
+ sandbox_id: str,
349
+ *,
350
+ gateway_url: str = IN_CLUSTER_GATEWAY_URL,
351
+ token_path: str = IN_CLUSTER_TOKEN_PATH,
352
+ ca_path: str = IN_CLUSTER_CA_PATH,
353
+ workspace: str = WORKSPACE,
354
+ **transport_options: Any,
355
+ ) -> Sandbox:
356
+ """A sandbox reached from a pod in the cluster: no DevZero credential.
357
+
358
+ The pod's projected ServiceAccount token (audience
359
+ ``sandbox-gateway.devzero.io``) and the operator's CA bundle are read
360
+ from ``/var/run/dz-sandbox/{token,ca.crt}``; the policy's
361
+ ``access.serviceAccounts`` must list the pod's ServiceAccount
362
+ (ADR-005 §In-cluster). Control-plane calls (``delete``, ``tokens``)
363
+ are not available on this route.
364
+ """
365
+ t = GatewayTransport.in_cluster(
366
+ policy,
367
+ sandbox_id,
368
+ gateway_url=gateway_url,
369
+ token_path=token_path,
370
+ ca_path=ca_path,
371
+ **transport_options,
372
+ )
373
+ info = pb.Sandbox(id=sandbox_id, policy=policy, status=pb.PHASE_READY)
374
+ return cls(info, transport=t, workspace=workspace)
375
+
376
+ # --- attributes ----------------------------------------------------------------
377
+
378
+ @property
379
+ def id(self) -> str:
380
+ return self.info.id
381
+
382
+ @property
383
+ def policy(self) -> str:
384
+ return self.info.policy
385
+
386
+ @property
387
+ def status(self) -> str:
388
+ return phase_name(self.info.status)
389
+
390
+ @property
391
+ def connect_url(self) -> str:
392
+ return self.info.connect.url
393
+
394
+ @property
395
+ def shutdown_at(self) -> datetime | None:
396
+ """When the sandbox is deleted unless extended (UTC), as DevZero last said."""
397
+ if not self.info.HasField("shutdown_at"):
398
+ return None
399
+ at: datetime = self.info.shutdown_at.ToDatetime(tzinfo=UTC)
400
+ return at
401
+
402
+ @property
403
+ def transport_kind(self) -> str:
404
+ """``"sse"``: REST/SSE/WebSocket, the Phase 1 data plane (see the module docstring)."""
405
+ return "sse"
406
+
407
+ @property
408
+ def transport(self) -> GatewayTransport:
409
+ if self._transport is None:
410
+ if not self.connect_url:
411
+ raise errors.DevZeroSandboxError(
412
+ f"sandbox {self.id} has no gateway URL yet (its cluster has no sandbox endpoint)"
413
+ )
414
+ options = dict(self._client.gateway_options) if self._client else {}
415
+ self._transport = GatewayTransport.external(
416
+ self.connect_url, self._token_credentials(), **options
417
+ )
418
+ if self._client is not None:
419
+ self._transport.on_gone = self._explain_gone
420
+ return self._transport
421
+
422
+ @property
423
+ def commands(self) -> Commands:
424
+ if self._commands is None:
425
+ self._commands = Commands(self.transport, workspace=self.workspace)
426
+ return self._commands
427
+
428
+ @property
429
+ def files(self) -> Files:
430
+ if self._files is None:
431
+ self._files = Files(self.transport, workspace=self.workspace)
432
+ return self._files
433
+
434
+ def terminal(
435
+ self,
436
+ cmd: Sequence[str] = ("/bin/bash",),
437
+ *,
438
+ cols: int = 120,
439
+ rows: int = 40,
440
+ env: Mapping[str, str] | None = None,
441
+ ) -> Terminal:
442
+ """Open an interactive terminal (WebSocket); close it to hang up."""
443
+ return Terminal(self.transport, cmd=cmd, cols=cols, rows=rows, env=env)
444
+
445
+ def kill(self, pid: int) -> None:
446
+ """Kill a process by pid (``commands.kill``)."""
447
+ self.commands.kill(pid)
448
+
449
+ def attach(self, pid: int) -> Process:
450
+ """``commands.attach``."""
451
+ return self.commands.attach(pid)
452
+
453
+ # --- control plane -------------------------------------------------------------
454
+
455
+ def _api(self) -> SandboxServiceClient:
456
+ if self._client is None:
457
+ raise errors.DevZeroSandboxError(
458
+ "this sandbox has no DevZero client (in-cluster mode); control-plane calls need one"
459
+ )
460
+ return self._client.api
461
+
462
+ def _token_credentials(self) -> TokenCredentials:
463
+ if self._credentials is None:
464
+ self._credentials = TokenCredentials()
465
+ return self._credentials
466
+
467
+ def refresh(self) -> Sandbox:
468
+ """Re-read the sandbox from DevZero."""
469
+ self.info = (
470
+ self._api()
471
+ .get_sandbox(pb.GetSandboxRequest(id=self.id), retry=True)
472
+ .sandbox
473
+ )
474
+ return self
475
+
476
+ def wait(self, timeout_s: float = 300) -> Sandbox:
477
+ """Follow ``WatchSandbox`` until the sandbox is ``ready``."""
478
+ api = self._api()
479
+ assert self._client is not None
480
+ clock, sleep = self._client._clock, self._client._sleep
481
+ deadline = clock() + timeout_s
482
+ cursor = ""
483
+ backoff = 0.5
484
+ while True:
485
+ status = self.status
486
+ if status == "ready":
487
+ if self.connect_url or self._transport is not None:
488
+ # The gateway's routing index may lag ready by seconds.
489
+ self.transport.mark_ready()
490
+ return self
491
+ if status in _TERMINAL_PHASES:
492
+ reason = self.info.status_reason
493
+ if status == "rejected":
494
+ raise errors.RejectedInCluster(
495
+ connect_code="failed_precondition",
496
+ code="rejected_in_cluster",
497
+ message=reason.message
498
+ or f"sandbox {self.id} was rejected by the cluster",
499
+ details={"reason": reason.code} if reason.code else None,
500
+ )
501
+ raise errors.SandboxFailed(self.id, status, reason.code, reason.message)
502
+ remaining = deadline - clock()
503
+ if remaining <= 0:
504
+ raise errors.SandboxWaitTimeout(self.id, status, timeout_s)
505
+ try:
506
+ for ev in api.watch_sandbox(
507
+ pb.WatchSandboxRequest(id=self.id, cursor=cursor),
508
+ timeout_s=remaining,
509
+ retry=True,
510
+ ):
511
+ cursor = ev.cursor or cursor
512
+ if ev.HasField("status_change"):
513
+ self.info.status = ev.status_change.status
514
+ self.info.status_reason.CopyFrom(ev.status_change.status_reason)
515
+ if self.status == "ready" or self.status in _TERMINAL_PHASES:
516
+ break
517
+ else:
518
+ # The server ended the watch (deleted, rejected, pruned):
519
+ # the sandbox row says where it stands.
520
+ self.refresh()
521
+ if self.status not in _TERMINAL_PHASES and self.status != "ready":
522
+ sleep(min(backoff, max(0.0, deadline - clock())))
523
+ backoff = min(backoff * 2, 5.0)
524
+ if self.status == "ready" and not self.connect_url:
525
+ self.refresh() # the create answer may predate the endpoint
526
+ except errors.ControlPlaneError as e:
527
+ if e.connect_code == "deadline_exceeded":
528
+ raise errors.SandboxWaitTimeout(
529
+ self.id, self.status, timeout_s
530
+ ) from None
531
+ if not e.retryable:
532
+ raise
533
+ sleep(min(backoff, max(0.0, deadline - clock())))
534
+ backoff = min(backoff * 2, 5.0)
535
+ self.refresh()
536
+
537
+ def extend(
538
+ self,
539
+ ttl: float | timedelta | None = None,
540
+ *,
541
+ until: datetime | None = None,
542
+ ) -> datetime:
543
+ """Keep the sandbox until ``now + ttl`` (seconds or a ``timedelta``), or ``until``.
544
+
545
+ Returns the new shutdown time, which DevZero clamps to the policy's
546
+ ``maxTTL`` from creation. The sandbox's tokens are unchanged: they
547
+ follow the live shutdown time (ADR-010 §TTL). Refusals:
548
+ :class:`~devzero_sandbox.errors.InvalidRequest` with
549
+ ``details['reason']`` ``ExtendTooShort`` (under 60 s past the current
550
+ shutdown time), ``ExtendTooLong`` (more than ``maxTTL`` past it) or
551
+ ``ShutdownBeforeCurrent``;
552
+ :class:`~devzero_sandbox.errors.MaxTTLReached` at the ceiling;
553
+ :class:`~devzero_sandbox.errors.SandboxNotExtendable` for a sandbox
554
+ that is not ready, pending, recreating or paused, or already expired.
555
+ """
556
+ if (ttl is None) == (until is None):
557
+ raise ValueError("extend takes exactly one of ttl or until")
558
+ if until is None:
559
+ assert ttl is not None
560
+ seconds = ttl.total_seconds() if isinstance(ttl, timedelta) else ttl
561
+ api = self._api()
562
+ assert self._client is not None
563
+ at = self._client._wall_clock() + float(seconds)
564
+ else:
565
+ if until.tzinfo is None:
566
+ raise ValueError(
567
+ "until must be timezone-aware (for example datetime.now(UTC))"
568
+ )
569
+ api = self._api()
570
+ at = until.timestamp()
571
+ # Whole seconds: DevZero truncates both times before comparing them.
572
+ req = pb.ExtendSandboxRequest(
573
+ id=self.id,
574
+ shutdown_at=Timestamp(seconds=int(at // 1)),
575
+ idempotency_key=f"sdk-{uuid.uuid4()}",
576
+ )
577
+ self.info = api.extend_sandbox(req, retry=True).sandbox
578
+ got = self.shutdown_at
579
+ if got is None:
580
+ raise errors.DevZeroSandboxError(
581
+ f"DevZero extended sandbox {self.id} but returned no shutdown time"
582
+ )
583
+ return got
584
+
585
+ def _explain_gone(self, err: errors.SandboxGone) -> None:
586
+ """Ask DevZero why the gateway calls the sandbox gone (once, no retries).
587
+
588
+ Only a deletion DevZero has recorded names the reason; a sandbox it
589
+ still believes live (the cluster's report is on its way) leaves the
590
+ gateway's own answer as it is.
591
+ """
592
+ try:
593
+ current = self._api().get_sandbox(pb.GetSandboxRequest(id=self.id)).sandbox
594
+ except errors.DevZeroSandboxError as e:
595
+ log.debug("could not ask DevZero why sandbox %s is gone: %s", self.id, e)
596
+ return
597
+ self.info = current
598
+ reason = (
599
+ current.status_reason
600
+ if self.status in ("terminating", "deleted")
601
+ else pb.StatusReason()
602
+ )
603
+ err.explain(self.status, reason.code, reason.message)
604
+
605
+ def delete(self) -> Sandbox:
606
+ """Delete the sandbox (DevZero revokes its tokens first) and close its connections."""
607
+ resp = self._api().delete_sandbox(
608
+ pb.DeleteSandboxRequest(id=self.id, idempotency_key=f"sdk-{uuid.uuid4()}"),
609
+ retry=True,
610
+ )
611
+ self.info = resp.sandbox
612
+ self.close()
613
+ return self
614
+
615
+ def close(self) -> None:
616
+ """Close the gateway connections (background processes keep running)."""
617
+ if self._transport is not None:
618
+ self._transport.close()
619
+
620
+ def __enter__(self) -> Self:
621
+ return self
622
+
623
+ def __exit__(
624
+ self,
625
+ exc_type: type[BaseException] | None,
626
+ exc: BaseException | None,
627
+ tb: TracebackType | None,
628
+ ) -> None:
629
+ self.close()
630
+
631
+ def __repr__(self) -> str:
632
+ return (
633
+ f"Sandbox(id={self.id!r}, policy={self.policy!r}, status={self.status!r})"
634
+ )