swarmbox-sdk 0.4.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,29 @@
1
+ """Async Python client for swarmbox."""
2
+
3
+ from swarmbox_sdk.client import (
4
+ BuildFailed,
5
+ Client,
6
+ ExecResult,
7
+ Image,
8
+ OpendsecError,
9
+ Readiness,
10
+ Sandbox,
11
+ SwarmboxError,
12
+ World,
13
+ WorldFailed,
14
+ context_tag,
15
+ )
16
+
17
+ __all__ = [
18
+ "BuildFailed",
19
+ "Client",
20
+ "ExecResult",
21
+ "Image",
22
+ "OpendsecError",
23
+ "Readiness",
24
+ "Sandbox",
25
+ "SwarmboxError",
26
+ "World",
27
+ "WorldFailed",
28
+ "context_tag",
29
+ ]
swarmbox_sdk/client.py ADDED
@@ -0,0 +1,409 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import io
6
+ import os
7
+ import tarfile
8
+ import warnings
9
+ from dataclasses import asdict, dataclass, field
10
+ from pathlib import Path, PurePosixPath
11
+
12
+ import httpx
13
+
14
+
15
+ # Old setting names already warned about in this process.
16
+ _warned: set[str] = set()
17
+
18
+
19
+ def env(name: str, default: str | None = None) -> str | None:
20
+ """The setting SWARMBOX_<name> from the environment.
21
+
22
+ Until 0.5.0 the name it had before the project was renamed,
23
+ OPENDSEC_<name>, is used when SWARMBOX_<name> is unset or empty, with a
24
+ FutureWarning: the kind Python shows to someone running a program, not
25
+ only to whoever wrote the calling code. Once per setting in a process:
26
+ a run of hundreds of trials reads each of them hundreds of times.
27
+ """
28
+ new, old = os.environ.get(f"SWARMBOX_{name}"), os.environ.get(f"OPENDSEC_{name}")
29
+ if new or old is None:
30
+ return default if new is None else new
31
+ if name in _warned:
32
+ return old
33
+ _warned.add(name)
34
+ warnings.warn(
35
+ f"OPENDSEC_{name} is used for now, but the project is renamed: set SWARMBOX_{name} instead",
36
+ FutureWarning,
37
+ stacklevel=2,
38
+ )
39
+ return old
40
+
41
+
42
+ class SwarmboxError(Exception):
43
+ """A request failed. `status` is the HTTP status when the API answered
44
+ with an error (503 means the platform had no capacity: retrying shortly
45
+ is safe), else None."""
46
+
47
+ def __init__(self, message: str, status: int | None = None):
48
+ super().__init__(message)
49
+ self.status = status
50
+
51
+
52
+ # The name this class had before the project was renamed; kept until 0.5.0 so
53
+ # that existing `except OpendsecError` clauses still catch.
54
+ OpendsecError = SwarmboxError
55
+
56
+
57
+ class WorldFailed(SwarmboxError):
58
+ """The World ended for an infra reason (not an agent failure); retry it."""
59
+
60
+ def __init__(self, world_id: str, reason: str):
61
+ super().__init__(f"world {world_id} failed: {reason}")
62
+ self.world_id = world_id
63
+ self.reason = reason
64
+
65
+
66
+ class BuildFailed(SwarmboxError):
67
+ """The platform could not build an image from its build context: the
68
+ Dockerfile failed, or the build timed out. `log` is the tail of the build's
69
+ output, where a failing step shows."""
70
+
71
+ def __init__(self, tag: str, error: str, log: str):
72
+ super().__init__(f"image build {tag} failed: {error}\n{log}")
73
+ self.tag = tag
74
+ self.error = error
75
+ self.log = log
76
+
77
+
78
+ @dataclass
79
+ class Image:
80
+ """An image the platform built for you. Pass `ref`, the image by digest
81
+ in the platform's registry, as a Sandbox's image."""
82
+
83
+ tag: str
84
+ #: The image by digest once it is ready; until then, the tag being built.
85
+ ref: str = ""
86
+ state: str = "" # "building", "ready" or "failed"
87
+ error: str = ""
88
+ log: str = ""
89
+ build_ms: int = 0
90
+ #: True if this call found the image already built.
91
+ cached: bool = False
92
+
93
+
94
+ # Never part of a build context: editor and OS clutter, and VCS metadata.
95
+ IGNORED_NAMES = frozenset({".DS_Store", ".git", "__pycache__"})
96
+
97
+
98
+ def _context_files(context: Path) -> list[Path]:
99
+ return [
100
+ p
101
+ for p in sorted(context.rglob("*"))
102
+ if p.is_file() and not any(part in IGNORED_NAMES for part in p.relative_to(context).parts)
103
+ ]
104
+
105
+
106
+ def context_tag(context: str | Path, dockerfile: str = "Dockerfile") -> str:
107
+ """The tag an image built from this context gets: a hash of every file's
108
+ path, exec bit and contents, and of the Dockerfile's name. Unchanged files
109
+ give the same tag, so a rebuild of them is a lookup."""
110
+ context = Path(context)
111
+ h = hashlib.sha256()
112
+
113
+ def add(*parts: str | bytes) -> None:
114
+ for p in parts:
115
+ b = p.encode() if isinstance(p, str) else p
116
+ h.update(len(b).to_bytes(8, "big") + b)
117
+
118
+ add("opendsec-context-v1", dockerfile)
119
+ for p in _context_files(context):
120
+ add(p.relative_to(context).as_posix(), oct(p.stat().st_mode & 0o111), p.read_bytes())
121
+ return h.hexdigest()[:32]
122
+
123
+
124
+ def _image(d: dict) -> Image:
125
+ known = Image.__dataclass_fields__.keys() - {"cached"}
126
+ return Image(**{k: v for k, v in d.items() if k in known})
127
+
128
+
129
+ def _context_tar(context: Path) -> bytes:
130
+ buf = io.BytesIO()
131
+ # Links are sent as the files they point to, which is what context_tag
132
+ # hashed: a link out of the context would dangle on the platform.
133
+ with tarfile.open(fileobj=buf, mode="w", dereference=True) as tar:
134
+ for p in _context_files(context):
135
+ tar.add(p, arcname=p.relative_to(context).as_posix(), recursive=False)
136
+ return buf.getvalue()
137
+
138
+
139
+ @dataclass
140
+ class Readiness:
141
+ command: list[str]
142
+ interval: str = "1s"
143
+ timeout: str = "60s"
144
+
145
+
146
+ @dataclass
147
+ class Sandbox:
148
+ """One container of a World."""
149
+
150
+ name: str
151
+ image: str
152
+ cpus: float = 1
153
+ memory_mb: int = 1024
154
+ command: list[str] | None = None
155
+ env: dict[str, str] = field(default_factory=dict)
156
+ workdir: str | None = None
157
+ aliases: list[str] = field(default_factory=list)
158
+ readiness: Readiness | None = None
159
+ egress: str = "none" # "none" or "public"
160
+
161
+ def to_json(self) -> dict:
162
+ d = {
163
+ "name": self.name,
164
+ "image": self.image,
165
+ "resources": {"cpus": self.cpus, "memory_mb": self.memory_mb},
166
+ "env": self.env,
167
+ "aliases": self.aliases,
168
+ "egress": self.egress,
169
+ }
170
+ if self.command:
171
+ d["command"] = self.command
172
+ if self.workdir:
173
+ d["workdir"] = self.workdir
174
+ if self.readiness:
175
+ d["readiness"] = asdict(self.readiness)
176
+ return d
177
+
178
+
179
+ @dataclass
180
+ class ExecResult:
181
+ exit_code: int
182
+ stdout: str
183
+ stderr: str
184
+ timed_out: bool = False
185
+ truncated: bool = False
186
+
187
+
188
+ class Client:
189
+ """Talks to a swarmbox apiserver.
190
+
191
+ Defaults come from SWARMBOX_URL and SWARMBOX_TOKEN.
192
+ """
193
+
194
+ def __init__(
195
+ self,
196
+ url: str | None = None,
197
+ token: str | None = None,
198
+ timeout: float = 600,
199
+ max_connections: int = 100,
200
+ ):
201
+ url = url or env("URL", "http://localhost:7700")
202
+ token = token or env("TOKEN")
203
+ if not token:
204
+ raise SwarmboxError("no API token: pass token= or set SWARMBOX_TOKEN")
205
+ # Each in-flight create or exec holds a connection for its whole
206
+ # duration, so concurrency above max_connections queues client-side.
207
+ self._http = httpx.AsyncClient(
208
+ base_url=url,
209
+ headers={"Authorization": f"Bearer {token}"},
210
+ timeout=timeout,
211
+ limits=httpx.Limits(max_connections=max_connections, max_keepalive_connections=max_connections),
212
+ )
213
+
214
+ async def __aenter__(self) -> Client:
215
+ return self
216
+
217
+ async def __aexit__(self, *exc) -> None:
218
+ await self.close()
219
+
220
+ async def close(self) -> None:
221
+ await self._http.aclose()
222
+
223
+ async def create_world(self, sandboxes: list[Sandbox], ttl: str = "1h") -> World:
224
+ """Create a World and wait until every Sandbox in it is ready."""
225
+ info = await self._request(
226
+ "POST", "/v1/worlds", json={"ttl": ttl, "sandboxes": [sb.to_json() for sb in sandboxes]}
227
+ )
228
+ if info["state"] == "failed":
229
+ raise WorldFailed(info["id"], info.get("reason", ""))
230
+ return World(self, info)
231
+
232
+ async def list_worlds(self) -> list[dict]:
233
+ """Your Worlds, on every node (the apiserver fans out). Other Users' are never listed."""
234
+ return (await self._request("GET", "/v1/worlds"))["worlds"]
235
+
236
+ async def get_world(self, world_id: str) -> World:
237
+ return World(self, await self._request("GET", f"/v1/worlds/{world_id}"))
238
+
239
+ async def get_image(self, tag: str) -> Image | None:
240
+ """Your image with this tag, or None if the platform has none."""
241
+ r = await self._http.get(f"/v1/images/{tag}")
242
+ if r.status_code == 404:
243
+ return None
244
+ return _image(self._json(r, "GET", f"/v1/images/{tag}"))
245
+
246
+ async def build_image(
247
+ self,
248
+ context: str | Path,
249
+ dockerfile: str = "Dockerfile",
250
+ *,
251
+ force: bool = False,
252
+ poll: float = 1.0,
253
+ timeout: float = 1800,
254
+ ) -> Image:
255
+ """The image built from a Dockerfile and its build context (a local
256
+ directory), building it on the platform first unless it already has
257
+ it (or `force`, which rebuilds without the platform's build cache).
258
+ Returns once it is ready; raises BuildFailed if it can't be built.
259
+ If too many of your builds are already queued, it waits its turn.
260
+
261
+ Images are built for the platform's nodes, so this works from any
262
+ machine, with no Docker. The image's `ref` runs on every node; a
263
+ tag is yours alone, so no other User's upload can replace it.
264
+ """
265
+ context = Path(context)
266
+ if not (context / dockerfile).is_file():
267
+ raise SwarmboxError(f"no {dockerfile} in the build context {context}")
268
+ tag = await asyncio.to_thread(context_tag, context, dockerfile)
269
+ img = await self.get_image(tag)
270
+ cached = img is not None and img.state == "ready"
271
+ deadline = asyncio.get_running_loop().time() + timeout
272
+ if img is None or img.state == "failed" or (force and img.state == "ready"):
273
+ body = await asyncio.to_thread(_context_tar, context)
274
+ params = {"dockerfile": dockerfile} | ({"force": "1"} if force else {})
275
+ backoff = poll
276
+ while True:
277
+ r = await self._http.put(f"/v1/images/{tag}", params=params, content=body)
278
+ # 429: too many of your builds are queued; wait for some to end.
279
+ if r.status_code != 429 or asyncio.get_running_loop().time() > deadline:
280
+ break
281
+ await asyncio.sleep(backoff)
282
+ backoff = min(backoff * 2, 30)
283
+ img = _image(self._json(r, "PUT", f"/v1/images/{tag}"))
284
+ while img.state == "building":
285
+ if asyncio.get_running_loop().time() > deadline:
286
+ raise SwarmboxError(f"image build {tag} still running after {timeout:.0f}s")
287
+ await asyncio.sleep(poll)
288
+ got = await self.get_image(tag)
289
+ if got is None:
290
+ raise SwarmboxError(f"image build {tag} disappeared (the builder restarted?); retry")
291
+ img = got
292
+ if img.state == "failed":
293
+ raise BuildFailed(tag, img.error, img.log)
294
+ img.cached = cached and not force
295
+ return img
296
+
297
+ async def _request(self, method: str, path: str, **kw) -> dict:
298
+ return self._json(await self._http.request(method, path, **kw), method, path)
299
+
300
+ @staticmethod
301
+ def _json(r: httpx.Response, method: str, path: str) -> dict:
302
+ if r.is_error:
303
+ try:
304
+ msg = r.json().get("error", r.text)
305
+ except ValueError:
306
+ msg = r.text
307
+ raise SwarmboxError(f"{method} {path}: {r.status_code} {msg}", status=r.status_code)
308
+ return r.json()
309
+
310
+
311
+ class World:
312
+ """A live World. Methods take the name of the Sandbox to act in."""
313
+
314
+ def __init__(self, client: Client, info: dict):
315
+ self._client = client
316
+ self.info = info
317
+
318
+ @property
319
+ def id(self) -> str:
320
+ return self.info["id"]
321
+
322
+ @property
323
+ def state(self) -> str:
324
+ return self.info["state"]
325
+
326
+ @property
327
+ def timings(self) -> dict[str, int]:
328
+ """Where create time went on the node, in milliseconds."""
329
+ return self.info.get("timings", {})
330
+
331
+ def _path(self, sandbox: str, op: str) -> str:
332
+ return f"/v1/worlds/{self.id}/sandboxes/{sandbox}/{op}"
333
+
334
+ async def exec(
335
+ self,
336
+ sandbox: str,
337
+ command: str | list[str],
338
+ *,
339
+ env: dict[str, str] | None = None,
340
+ workdir: str | None = None,
341
+ timeout: float | None = None,
342
+ ) -> ExecResult:
343
+ """Run a command in a Sandbox. A string is run with `bash -lc`."""
344
+ if isinstance(command, str):
345
+ command = ["bash", "-lc", command]
346
+ body: dict = {"command": command, "env": env or {}}
347
+ if workdir:
348
+ body["workdir"] = workdir
349
+ if timeout:
350
+ body["timeout"] = timeout
351
+ try:
352
+ res = await self._client._request("POST", self._path(sandbox, "exec"), json=body)
353
+ except SwarmboxError:
354
+ await self._raise_if_failed()
355
+ raise
356
+ return ExecResult(**res)
357
+
358
+ async def upload(self, sandbox: str, local: str | Path, remote: str) -> None:
359
+ """Copy a local file or directory to `remote` inside a Sandbox."""
360
+ local = Path(local)
361
+ remote_p = PurePosixPath(remote)
362
+ buf = io.BytesIO()
363
+ with tarfile.open(fileobj=buf, mode="w") as tar:
364
+ if local.is_dir():
365
+ for child in sorted(local.iterdir()):
366
+ tar.add(child, arcname=child.name)
367
+ target_dir = str(remote_p)
368
+ else:
369
+ tar.add(local, arcname=remote_p.name)
370
+ target_dir = str(remote_p.parent)
371
+ await self._client._request(
372
+ "PUT", self._path(sandbox, "archive"), params={"path": target_dir}, content=buf.getvalue()
373
+ )
374
+
375
+ async def download(self, sandbox: str, remote: str, local: str | Path) -> None:
376
+ """Copy a file or directory at `remote` inside a Sandbox to `local`."""
377
+ r = await self._client._http.get(self._path(sandbox, "archive"), params={"path": remote})
378
+ if r.is_error:
379
+ raise SwarmboxError(f"download {remote}: {r.status_code} {r.text}")
380
+ local = Path(local)
381
+ name = PurePosixPath(remote).name
382
+ with tarfile.open(fileobj=io.BytesIO(r.content), mode="r") as tar:
383
+ if tar.getmember(name).isdir():
384
+ local.mkdir(parents=True, exist_ok=True)
385
+ for m in tar.getmembers():
386
+ if m.name == name:
387
+ continue
388
+ m.name = m.name[len(name) + 1 :]
389
+ tar.extract(m, local, filter="data")
390
+ else:
391
+ local.parent.mkdir(parents=True, exist_ok=True)
392
+ f = tar.extractfile(name)
393
+ assert f is not None
394
+ local.write_bytes(f.read())
395
+
396
+ async def refresh(self) -> World:
397
+ self.info = await self._client._request("GET", f"/v1/worlds/{self.id}")
398
+ return self
399
+
400
+ async def stop(self) -> None:
401
+ self.info = await self._client._request("DELETE", f"/v1/worlds/{self.id}")
402
+
403
+ async def _raise_if_failed(self) -> None:
404
+ try:
405
+ await self.refresh()
406
+ except SwarmboxError:
407
+ return
408
+ if self.state == "failed":
409
+ raise WorldFailed(self.id, self.info.get("reason", ""))
@@ -0,0 +1,18 @@
1
+ """Harbor environment provider for swarmbox: each Harbor trial runs as one World.
2
+
3
+ Needs the `harbor` extra: pip install 'swarmbox-sdk[harbor]'. Harbor loads it as
4
+ --environment-import-path swarmbox_sdk.harbor:SwarmboxEnvironment.
5
+ """
6
+
7
+ try:
8
+ from swarmbox_sdk.harbor.environment import SwarmboxEnvironment
9
+ except ModuleNotFoundError as e: # Harbor or PyYAML missing: the extra isn't installed
10
+ if e.name not in ("harbor", "yaml") and not (e.name or "").startswith("harbor."):
11
+ raise
12
+ raise ModuleNotFoundError(
13
+ f"swarmbox_sdk.harbor needs the harbor extra ({e.name} is not installed): "
14
+ "pip install 'swarmbox-sdk[harbor]'",
15
+ name=e.name,
16
+ ) from e
17
+
18
+ __all__ = ["SwarmboxEnvironment"]
@@ -0,0 +1,183 @@
1
+ """Translate the subset of docker-compose Harbor tasks use into a World's Sandboxes.
2
+
3
+ Anything outside the subset is rejected, never approximated: a silently
4
+ dropped key (a missing alias, a missing mount) produces a degraded task setup that
5
+ can still score, which is worse than a trial that refuses to start.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import shlex
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ import yaml
15
+
16
+ MAIN = "main"
17
+
18
+ SUPPORTED_KEYS = {
19
+ "image",
20
+ "build",
21
+ "command",
22
+ "environment",
23
+ "volumes",
24
+ "expose",
25
+ "networks",
26
+ "healthcheck",
27
+ "depends_on",
28
+ }
29
+
30
+
31
+ class UnsupportedCompose(ValueError):
32
+ pass
33
+
34
+
35
+ @dataclass
36
+ class FileMount:
37
+ source: Path # on the host, resolved against the compose file's directory
38
+ target: str # inside the Sandbox
39
+
40
+
41
+ @dataclass
42
+ class ServicePlan:
43
+ """One compose service, before images are built and pushed."""
44
+
45
+ name: str
46
+ image: str | None = None
47
+ build_context: Path | None = None
48
+ dockerfile: str | None = None
49
+ command: list[str] | None = None
50
+ env: dict[str, str] = field(default_factory=dict)
51
+ files: list[FileMount] = field(default_factory=list)
52
+ aliases: list[str] = field(default_factory=list)
53
+ readiness: list[str] | None = None
54
+ readiness_interval_s: float = 1.0
55
+ readiness_timeout_s: float = 60.0
56
+
57
+
58
+ def plan_services(
59
+ environment_dir: Path, docker_image: str | None, prefer_prebuilt: bool
60
+ ) -> list[ServicePlan]:
61
+ """Harbor's base `main` service merged with the task's compose file."""
62
+ main = ServicePlan(name=MAIN, command=["sh", "-c", "sleep infinity"])
63
+ dockerfile = environment_dir / "Dockerfile"
64
+ if docker_image and (prefer_prebuilt or not dockerfile.exists()):
65
+ main.image = docker_image
66
+ elif dockerfile.exists():
67
+ main.build_context = environment_dir
68
+ plans = {MAIN: main}
69
+
70
+ compose_path = environment_dir / "docker-compose.yaml"
71
+ if compose_path.exists():
72
+ doc = yaml.safe_load(compose_path.read_text()) or {}
73
+ if extra := set(doc) - {"services"}:
74
+ raise UnsupportedCompose(f"top-level keys not supported: {sorted(extra)}")
75
+ for name, svc in (doc.get("services") or {}).items():
76
+ plans[name] = _merge(plans.get(name) or ServicePlan(name=name), svc or {}, environment_dir)
77
+
78
+ for p in plans.values():
79
+ if not p.image and not p.build_context:
80
+ raise UnsupportedCompose(f"service {p.name!r} has neither image nor build")
81
+ return list(plans.values())
82
+
83
+
84
+ def _merge(p: ServicePlan, svc: dict, base: Path) -> ServicePlan:
85
+ if extra := set(svc) - SUPPORTED_KEYS:
86
+ raise UnsupportedCompose(f"service {p.name!r}: keys not supported: {sorted(extra)}")
87
+ if "image" in svc:
88
+ p.image = svc["image"]
89
+ if "build" in svc:
90
+ b = svc["build"]
91
+ if isinstance(b, str):
92
+ b = {"context": b}
93
+ if extra := set(b) - {"context", "dockerfile"}:
94
+ raise UnsupportedCompose(f"service {p.name!r}: build keys not supported: {sorted(extra)}")
95
+ p.build_context = (base / b.get("context", ".")).resolve()
96
+ p.dockerfile = b.get("dockerfile")
97
+ p.image = None
98
+ if "command" in svc:
99
+ c = svc["command"]
100
+ p.command = shlex.split(c) if isinstance(c, str) else [str(x) for x in c]
101
+ if "environment" in svc:
102
+ env = svc["environment"]
103
+ if isinstance(env, list):
104
+ env = dict(e.split("=", 1) for e in env)
105
+ p.env.update({k: str(v) for k, v in env.items()})
106
+ for v in svc.get("volumes", []):
107
+ p.files.append(_file_mount(p.name, v, base))
108
+ p.aliases += _aliases(p.name, svc.get("networks"))
109
+ if "healthcheck" in svc:
110
+ _readiness(p, svc["healthcheck"])
111
+ # depends_on is satisfied by construction: a World is ready only when
112
+ # every Sandbox's readiness probe passes, and nothing runs before that.
113
+ for dep, cond in _depends_on(svc.get("depends_on")).items():
114
+ if cond not in ("service_started", "service_healthy"):
115
+ raise UnsupportedCompose(f"service {p.name!r}: depends_on {dep} condition {cond!r}")
116
+ return p
117
+
118
+
119
+ def _file_mount(service: str, v, base: Path) -> FileMount:
120
+ if not isinstance(v, str):
121
+ raise UnsupportedCompose(f"service {service!r}: long-form volumes not supported")
122
+ parts = v.split(":")
123
+ if len(parts) not in (2, 3) or not parts[0].startswith("."):
124
+ raise UnsupportedCompose(
125
+ f"service {service!r}: only read-only binds of task files are supported, got {v!r}"
126
+ )
127
+ if len(parts) == 3 and parts[2] != "ro":
128
+ raise UnsupportedCompose(f"service {service!r}: volume {v!r} must be :ro")
129
+ src = (base / parts[0]).resolve()
130
+ if not src.exists():
131
+ raise UnsupportedCompose(f"service {service!r}: volume source {src} does not exist")
132
+ return FileMount(source=src, target=parts[1])
133
+
134
+
135
+ def _aliases(service: str, networks) -> list[str]:
136
+ if networks is None or isinstance(networks, list):
137
+ if networks and networks != ["default"]:
138
+ raise UnsupportedCompose(f"service {service!r}: only the default network is supported")
139
+ return []
140
+ out = []
141
+ for net, cfg in networks.items():
142
+ if net != "default":
143
+ raise UnsupportedCompose(f"service {service!r}: only the default network is supported")
144
+ cfg = cfg or {}
145
+ if extra := set(cfg) - {"aliases"}:
146
+ raise UnsupportedCompose(f"service {service!r}: network keys not supported: {sorted(extra)}")
147
+ out += cfg.get("aliases", [])
148
+ return out
149
+
150
+
151
+ def _readiness(p: ServicePlan, hc: dict) -> None:
152
+ if extra := set(hc) - {"test", "interval", "timeout", "retries", "start_period"}:
153
+ raise UnsupportedCompose(f"service {p.name!r}: healthcheck keys not supported: {sorted(extra)}")
154
+ test = hc["test"]
155
+ if isinstance(test, str):
156
+ p.readiness = ["sh", "-c", test]
157
+ elif test[0] == "CMD":
158
+ p.readiness = [str(x) for x in test[1:]]
159
+ elif test[0] == "CMD-SHELL":
160
+ p.readiness = ["sh", "-c", test[1]]
161
+ else:
162
+ raise UnsupportedCompose(f"service {p.name!r}: healthcheck test {test[0]!r}")
163
+ interval = _seconds(hc.get("interval", "30s"))
164
+ p.readiness_interval_s = interval
165
+ p.readiness_timeout_s = _seconds(hc.get("start_period", "0s")) + interval * hc.get("retries", 3)
166
+
167
+
168
+ def _depends_on(d) -> dict[str, str]:
169
+ if d is None:
170
+ return {}
171
+ if isinstance(d, list):
172
+ return {k: "service_started" for k in d}
173
+ return {k: (v or {}).get("condition", "service_started") for k, v in d.items()}
174
+
175
+
176
+ def _seconds(s) -> float:
177
+ if isinstance(s, (int, float)):
178
+ return float(s)
179
+ units = {"ms": 0.001, "s": 1, "m": 60, "h": 3600}
180
+ for u in ("ms", "s", "m", "h"):
181
+ if s.endswith(u) and s[: -len(u)].replace(".", "", 1).isdigit():
182
+ return float(s[: -len(u)]) * units[u]
183
+ raise UnsupportedCompose(f"duration {s!r}")