zipbox 0.1.2__tar.gz → 0.1.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: zipbox
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: Drive Zipbox boxes from Python: create, exec, files, PTY, previews.
5
5
  Project-URL: Homepage, https://zipbox.ai
6
6
  Project-URL: Documentation, https://zipbox.ai/docs/sdk-python
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "zipbox"
7
- version = "0.1.2"
7
+ version = "0.1.4"
8
8
  description = "Drive Zipbox boxes from Python: create, exec, files, PTY, previews."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -111,19 +111,33 @@ class AsyncSandboxes:
111
111
  name: str | None = None,
112
112
  tier: Tier | None = None,
113
113
  ssh_public_key: str | None = None,
114
+ mailbox: bool | None = None,
114
115
  ) -> AsyncSandbox:
115
- """Create a box and wait until it is ready (no deadline)."""
116
+ """Create a box and wait until it is ready (no deadline).
117
+
118
+ ``mailbox=True`` creates the box's mailbox now; by default it is created
119
+ the first time the box uses mail.
120
+ """
116
121
  detail = await self._client._run(
117
- self._client._core.create(name=name, tier=tier, ssh_public_key=ssh_public_key)
122
+ self._client._core.create(
123
+ name=name, tier=tier, ssh_public_key=ssh_public_key, mailbox=mailbox
124
+ )
118
125
  )
119
126
  return AsyncSandbox(self._client, detail.id, detail)
120
127
 
121
128
  async def get_or_create(
122
- self, name: str, *, tier: Tier | None = None, ssh_public_key: str | None = None
129
+ self,
130
+ name: str,
131
+ *,
132
+ tier: Tier | None = None,
133
+ ssh_public_key: str | None = None,
134
+ mailbox: bool | None = None,
123
135
  ) -> AsyncSandbox:
124
136
  """Return the live box named ``name`` (starting it if stopped), or create it."""
125
137
  detail = await self._client._run(
126
- self._client._core.get_or_create(name, tier=tier, ssh_public_key=ssh_public_key)
138
+ self._client._core.get_or_create(
139
+ name, tier=tier, ssh_public_key=ssh_public_key, mailbox=mailbox
140
+ )
127
141
  )
128
142
  return AsyncSandbox(self._client, detail.id, detail)
129
143
 
@@ -109,19 +109,33 @@ class Sandboxes:
109
109
  name: str | None = None,
110
110
  tier: Tier | None = None,
111
111
  ssh_public_key: str | None = None,
112
+ mailbox: bool | None = None,
112
113
  ) -> Sandbox:
113
- """Create a box and wait until it is ready (no deadline)."""
114
+ """Create a box and wait until it is ready (no deadline).
115
+
116
+ ``mailbox=True`` creates the box's mailbox now; by default it is created
117
+ the first time the box uses mail.
118
+ """
114
119
  detail = self._client._run(
115
- self._client._core.create(name=name, tier=tier, ssh_public_key=ssh_public_key)
120
+ self._client._core.create(
121
+ name=name, tier=tier, ssh_public_key=ssh_public_key, mailbox=mailbox
122
+ )
116
123
  )
117
124
  return Sandbox(self._client, detail.id, detail)
118
125
 
119
126
  def get_or_create(
120
- self, name: str, *, tier: Tier | None = None, ssh_public_key: str | None = None
127
+ self,
128
+ name: str,
129
+ *,
130
+ tier: Tier | None = None,
131
+ ssh_public_key: str | None = None,
132
+ mailbox: bool | None = None,
121
133
  ) -> Sandbox:
122
134
  """Return the live box named ``name`` (starting it if stopped), or create it."""
123
135
  detail = self._client._run(
124
- self._client._core.get_or_create(name, tier=tier, ssh_public_key=ssh_public_key)
136
+ self._client._core.get_or_create(
137
+ name, tier=tier, ssh_public_key=ssh_public_key, mailbox=mailbox
138
+ )
125
139
  )
126
140
  return Sandbox(self._client, detail.id, detail)
127
141
 
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import base64
6
6
  import json
7
+ import math
7
8
  import os
8
9
  import posixpath
9
10
  import random
@@ -40,7 +41,7 @@ from zipbox._models import (
40
41
  )
41
42
  from zipbox._sse import SseMessage, SseParser
42
43
 
43
- VERSION = "0.1.2"
44
+ VERSION = "0.1.4"
44
45
  DEFAULT_API_URL = "https://api.tribes.xyz"
45
46
  WORKSPACE = "/root/workspace"
46
47
  _USER_AGENT = f"zipbox-python/{VERSION}"
@@ -230,8 +231,8 @@ class BoxTarget:
230
231
 
231
232
  @property
232
233
  def host(self) -> str:
233
- """The box's hostname (no port)."""
234
- return urlparse(self.base_url).hostname or ""
234
+ """The custom preview apex, without the platform transport prefix or port."""
235
+ return (urlparse(self.base_url).hostname or "").removeprefix("box--")
235
236
 
236
237
 
237
238
  class Core:
@@ -421,6 +422,7 @@ class Core:
421
422
  name: str | None = None,
422
423
  tier: str | None = None,
423
424
  ssh_public_key: str | None = None,
425
+ mailbox: bool | None = None,
424
426
  ) -> Op[SandboxDetail]:
425
427
  """Claim a box (idempotent) and wait until it is ready."""
426
428
  body: dict[str, Any] = {}
@@ -430,6 +432,8 @@ class Core:
430
432
  body["tier"] = tier
431
433
  if ssh_public_key is not None:
432
434
  body["sshPublicKey"] = ssh_public_key
435
+ if mailbox is not None:
436
+ body["mailbox"] = mailbox
433
437
  created = yield from self.control(
434
438
  "POST",
435
439
  "/sandbox/identity/claim",
@@ -440,7 +444,12 @@ class Core:
440
444
  return (yield from self.wait_ready(str(created["sandboxId"])))
441
445
 
442
446
  def get_or_create(
443
- self, name: str, *, tier: str | None = None, ssh_public_key: str | None = None
447
+ self,
448
+ name: str,
449
+ *,
450
+ tier: str | None = None,
451
+ ssh_public_key: str | None = None,
452
+ mailbox: bool | None = None,
444
453
  ) -> Op[SandboxDetail]:
445
454
  """The live box with this name, started if stopped; created if there is none."""
446
455
  boxes = yield from self.list_sandboxes()
@@ -449,7 +458,11 @@ class Core:
449
458
  if box.status == "archived" or box.is_archived:
450
459
  yield from self.start(box.id)
451
460
  return (yield from self.wait_ready(box.id))
452
- return (yield from self.create(name=name, tier=tier, ssh_public_key=ssh_public_key))
461
+ return (
462
+ yield from self.create(
463
+ name=name, tier=tier, ssh_public_key=ssh_public_key, mailbox=mailbox
464
+ )
465
+ )
453
466
 
454
467
  def lifecycle(self, sandbox_id: str, action: str, body: Any = None) -> Op[None]:
455
468
  """POST /sandbox/:id/<action>."""
@@ -665,13 +678,41 @@ class Core:
665
678
  target = yield from self.target(sandbox_id)
666
679
  chosen = label or f"p{port}"
667
680
  host = f"{chosen}.{target.host}"
668
- result = yield from self.exec(
669
- sandbox_id, exec_body(["tribes-caddy", "add", host, f"127.0.0.1:{port}"])
670
- )
671
- if result.exit_code != 0:
672
- raise ZipboxError(
673
- "conflict", f"tribes-caddy add failed: {(result.stderr or result.stdout).strip()}"
674
- )
681
+ backoff = self._backoff()
682
+ while True:
683
+ retry_after = 0.0
684
+ try:
685
+ result = yield from self.exec(
686
+ sandbox_id,
687
+ exec_body(["tribes-caddy", "add", host, f"127.0.0.1:{port}", "--no-wait"]),
688
+ )
689
+ if result.exit_code == 0:
690
+ break
691
+ if result.exit_code != 75:
692
+ raise ZipboxError(
693
+ "conflict",
694
+ f"tribes-caddy add failed: {(result.stderr or result.stdout).strip()}",
695
+ )
696
+ try:
697
+ pending = json.loads(result.stdout.strip().splitlines()[-1])
698
+ delay = pending["retryAfterMs"]
699
+ if (
700
+ pending.get("status") != "pending"
701
+ or not isinstance(delay, (int, float))
702
+ or not math.isfinite(delay)
703
+ or delay < 0
704
+ ):
705
+ raise ValueError("invalid pending status")
706
+ retry_after = delay / 1000
707
+ except (ValueError, KeyError, IndexError, TypeError) as error:
708
+ raise ZipboxError(
709
+ "conflict", "preview returned invalid pending status"
710
+ ) from error
711
+ except ZipboxError as error:
712
+ if not error.retryable:
713
+ raise
714
+ retry_after = (error.retry_after_ms or 0) / 1000
715
+ yield Sleep(max(backoff.next(), retry_after))
675
716
  return Preview(url=f"https://{host}", label=chosen)
676
717
 
677
718
  def unpreview(self, sandbox_id: str, label: str) -> Op[None]:
@@ -91,7 +91,9 @@ def run_sync_op(zb: Zipbox, op: str, a: dict[str, Any]) -> Any:
91
91
  case "sandboxes.get":
92
92
  return zb.sandboxes.get(a["id"])
93
93
  case "sandboxes.create":
94
- return zb.sandboxes.create(name=a.get("name"), tier=a.get("tier"))
94
+ return zb.sandboxes.create(
95
+ name=a.get("name"), tier=a.get("tier"), mailbox=a.get("mailbox")
96
+ )
95
97
  case "sandboxes.start":
96
98
  return zb.sandboxes.start(a["id"])
97
99
  case "sandboxes.stop":
@@ -143,7 +145,9 @@ async def run_async_op(zb: AsyncZipbox, op: str, a: dict[str, Any]) -> Any:
143
145
  case "sandboxes.get":
144
146
  return await zb.sandboxes.get(a["id"])
145
147
  case "sandboxes.create":
146
- return await zb.sandboxes.create(name=a.get("name"), tier=a.get("tier"))
148
+ return await zb.sandboxes.create(
149
+ name=a.get("name"), tier=a.get("tier"), mailbox=a.get("mailbox")
150
+ )
147
151
  case "sandboxes.start":
148
152
  return await zb.sandboxes.start(a["id"])
149
153
  case "sandboxes.stop":
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import time
7
+ from typing import Any
7
8
 
8
9
  import httpx
9
10
  import pytest
@@ -13,6 +14,7 @@ from zipbox._backoff import Backoff
13
14
  from zipbox._core import _SCREENSHOT, BoxTarget, Core, exec_body, resolve_config, resolve_path
14
15
  from zipbox._effects import HttpRequest, HttpResponse, Sleep
15
16
  from zipbox._errors import code_for_status, error_from_response, parse_retry_after_ms
17
+ from zipbox._models import ExecResult
16
18
  from zipbox._sse import SseParser
17
19
  from zipbox._transport import _network_error
18
20
 
@@ -217,3 +219,57 @@ def test_a_second_401_says_the_box_has_not_received_a_live_key() -> None:
217
219
  op.send(HttpResponse(401, {}, b""))
218
220
  assert caught.value.code == "unauthorized" and caught.value.retryable is True
219
221
  assert "has not received" in caught.value.message
222
+
223
+
224
+ @pytest.mark.parametrize(
225
+ ("origin", "apex"),
226
+ [
227
+ ("https://box--demo.zbox.sh", "demo.zbox.sh"),
228
+ ("https://box--box--demo.zbox.sh", "box--demo.zbox.sh"),
229
+ ("https://demo.zbox.sh", "demo.zbox.sh"),
230
+ ("https://mailbox--demo.zbox.sh", "mailbox--demo.zbox.sh"),
231
+ ("http://127.0.0.1:9100", "127.0.0.1"),
232
+ ],
233
+ )
234
+ def test_preview_apex_preserves_the_transport_origin(origin: str, apex: str) -> None:
235
+ target = BoxTarget(origin, "bt_test")
236
+ assert target.host == apex
237
+ assert target.base_url == origin
238
+
239
+
240
+ def test_preview_pending_beyond30_seconds_uses_same_operation(
241
+ monkeypatch: pytest.MonkeyPatch,
242
+ ) -> None:
243
+ core = Core(resolve_config("key", "https://api.test", 0))
244
+ core._targets["box"] = BoxTarget("https://box--demo.zbox.sh", "bt")
245
+ calls: list[dict[str, Any]] = []
246
+
247
+ def execute(_box: str, body: dict[str, Any]) -> Any:
248
+ calls.append(body)
249
+ if False:
250
+ yield None
251
+ pending = len(calls) <= 16
252
+ return ExecResult(
253
+ id="p",
254
+ exit_code=75 if pending else 0,
255
+ stdout=json.dumps({"status": "pending", "retryAfterMs": 31_000}) if pending else "",
256
+ stderr="",
257
+ )
258
+
259
+ monkeypatch.setattr(core, "exec", execute)
260
+ op = core.preview("box", 4000, "web")
261
+ elapsed = 0.0
262
+ for _ in range(16):
263
+ effect = op.send(None)
264
+ assert isinstance(effect, Sleep)
265
+ assert effect.seconds >= 31
266
+ elapsed += effect.seconds
267
+ assert elapsed > 30
268
+ with pytest.raises(StopIteration) as completed:
269
+ op.send(None)
270
+ assert completed.value.value.url == "https://web.demo.zbox.sh"
271
+ assert (
272
+ calls
273
+ == [{"argv": ["tribes-caddy", "add", "web.demo.zbox.sh", "127.0.0.1:4000", "--no-wait"]}]
274
+ * 17
275
+ )
@@ -845,7 +845,7 @@ wheels = [
845
845
 
846
846
  [[package]]
847
847
  name = "zipbox"
848
- version = "0.1.2"
848
+ version = "0.1.4"
849
849
  source = { editable = "." }
850
850
  dependencies = [
851
851
  { name = "certifi" },
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes