diff --git a/.github/workflows/contract.yml b/.github/workflows/contract.yml new file mode 100644 index 0000000..dac304f --- /dev/null +++ b/.github/workflows/contract.yml @@ -0,0 +1,19 @@ +# @generated by Hollywood. Do not edit by hand. + +name: Generated API contract +on: + push: {} + pull_request: {} +permissions: + contents: read +jobs: + contract: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + - name: Test contract guard + run: python3 scripts/test-contract.py + shell: bash + - name: Verify pinned public operations + run: python3 scripts/check-contract.py + shell: bash diff --git a/.github/workflows/sdk-ci.yml b/.github/workflows/sdk-ci.yml index d9f0022..6086fbb 100644 --- a/.github/workflows/sdk-ci.yml +++ b/.github/workflows/sdk-ci.yml @@ -20,6 +20,8 @@ jobs: python-version: "3.11" - run: python -m pip install --upgrade build - run: python -m build + - run: python -m pip install dist/*.whl pytest pytest-asyncio + - run: python -m pytest tests -q # Verification only, never auto-fix: the SDK is generated formatted, so a diff here means # either hand-edited custom code or a regenerate that was not committed. ruff is pinned to # the release that produced these bytes, since a formatter minor can change them. diff --git a/README.md b/README.md index de9b72d..b70adfa 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ The full API of this library can be found in [api.md](./api.md). - [Installation](#installation) - [Usage](#usage) +- [Image import](#image-import) - [API Reference](./api.md) - [Async](#async) - [Authentication](#authentication) @@ -31,6 +32,53 @@ pip install dedalus-sdk
+## Image import + +```python +from dedalus_sdk import Dedalus +from dedalus_sdk.images import import_image, poll_image + +with Dedalus() as client: + ready = import_image(client, "my-app.tar", name="my-app", platform="linux/amd64") + + # Return after upload and registration, then wait later. + accepted = import_image(client, "my-app.tar", wait=False) + image = poll_image(client, accepted["image_id"]) +``` + +Async clients use `async_import_image` and `async_poll_image` with the same options: + +```python +from dedalus_sdk import AsyncDedalus +from dedalus_sdk.images import async_import_image + +async with AsyncDedalus() as client: + ready = await async_import_image(client, "my-app.tar") +``` + +The helpers stream a `docker save` archive, register it, and wait for readiness by +default. Set `wait=False` to return after registration. `timeout` defaults to 3,600 +seconds for the import and `poll_interval` defaults to 2 seconds. `on_progress` +receives each observed image. `ImagePreparationError.image` preserves the image ID +on terminal failure or polling deadline expiry; timeout or task cancellation does +not cancel server preparation. + +The synchronous helper checks its deadline between I/O operations, uses the +remaining budget for request inactivity timeouts, and disables automatic API +retries. The async helper enforces its deadline with task cancellation and retains +the client's retry policy. Use the same `idempotency_key` when retrying an import +with unchanged input. + +Archives must be regular, nonempty files of at most 5 GiB. Storage uploads use a +separate HTTP client without API credentials. The helpers require the image API +to be deployed and enabled for your organization; they do not bypass access controls. + +Custom image imports currently require an Ubuntu 24.04 `linux/amd64` Docker-save +archive. On Apple silicon, build or pull with `--platform linux/amd64` before +saving the archive. The image provides the filesystem; container entrypoint, +CMD, environment, working directory, and user settings are not applied. Start +processes using Machine exec or SSH after the Machine reaches running. + ## Usage ```python diff --git a/api-contract.json b/api-contract.json new file mode 100644 index 0000000..c7418c4 --- /dev/null +++ b/api-contract.json @@ -0,0 +1,202 @@ +{ + "source_sha": "9f8d54f123e81b8bc7252f855c52ecbf7cc8ae42", + "spec_sha256": "c0b2db893e3017c5c83c14375e6085581584641f617ee7ea1305ab80e9b50421", + "operations": [ + { + "method": "GET", + "path": "/v1/images", + "bodyParams": [] + }, + { + "method": "POST", + "path": "/v1/images", + "bodyParams": [ + "credential_ref", + "name", + "platform", + "source" + ] + }, + { + "method": "POST", + "path": "/v1/images/uploads", + "bodyParams": [ + "platform", + "sha256", + "size_bytes" + ] + }, + { + "method": "DELETE", + "path": "/v1/images/{image_id}", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/images/{image_id}", + "bodyParams": [] + }, + { + "method": "PATCH", + "path": "/v1/images/{image_id}", + "bodyParams": [ + "name" + ] + }, + { + "method": "GET", + "path": "/v1/machines", + "bodyParams": [] + }, + { + "method": "POST", + "path": "/v1/machines", + "bodyParams": [ + "autosleep", + "image_id", + "memory_mib", + "storage_gib", + "vcpu" + ] + }, + { + "method": "DELETE", + "path": "/v1/machines/{machine_id}", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}", + "bodyParams": [] + }, + { + "method": "PATCH", + "path": "/v1/machines/{machine_id}", + "bodyParams": [ + "autosleep", + "storage_gib" + ] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}/autoresizing", + "bodyParams": [] + }, + { + "method": "PATCH", + "path": "/v1/machines/{machine_id}/autoresizing", + "bodyParams": [ + "cpu", + "cpu_max_vcpu", + "memory", + "memory_max_mib" + ] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}/executions", + "bodyParams": [] + }, + { + "method": "POST", + "path": "/v1/machines/{machine_id}/executions", + "bodyParams": [ + "command", + "cwd", + "env", + "stdin", + "timeout_ms" + ] + }, + { + "method": "DELETE", + "path": "/v1/machines/{machine_id}/executions/{execution_id}", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}/executions/{execution_id}", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}/executions/{execution_id}/events", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}/executions/{execution_id}/logs", + "bodyParams": [] + }, + { + "method": "POST", + "path": "/v1/machines/{machine_id}/executions/{execution_id}/logs/token", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}/executions/{execution_id}/output", + "bodyParams": [] + }, + { + "method": "POST", + "path": "/v1/machines/{machine_id}/reboot", + "bodyParams": [] + }, + { + "method": "POST", + "path": "/v1/machines/{machine_id}/resize", + "bodyParams": [ + "memory_mib", + "vcpu" + ] + }, + { + "method": "POST", + "path": "/v1/machines/{machine_id}/sleep", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}/ssh", + "bodyParams": [] + }, + { + "method": "POST", + "path": "/v1/machines/{machine_id}/ssh", + "bodyParams": [ + "public_key" + ] + }, + { + "method": "DELETE", + "path": "/v1/machines/{machine_id}/ssh/{session_id}", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/machines/{machine_id}/ssh/{session_id}", + "bodyParams": [] + }, + { + "method": "POST", + "path": "/v1/machines/{machine_id}/wake", + "bodyParams": [] + }, + { + "method": "GET", + "path": "/v1/organization/autoresizing", + "bodyParams": [] + }, + { + "method": "PATCH", + "path": "/v1/organization/autoresizing", + "bodyParams": [ + "cpu", + "cpu_max_vcpu", + "memory", + "memory_max_mib" + ] + } + ] +} diff --git a/ci/contract.ts b/ci/contract.ts new file mode 100644 index 0000000..488e41c --- /dev/null +++ b/ci/contract.ts @@ -0,0 +1,24 @@ +import { command, workflow } from '@dedalus-labs/hollywood'; + +// Generate with Hollywood 0.0.5; this workflow never publishes packages. +export const contractCI = workflow({ + name: 'Generated API contract', + on: { push: {}, pull_request: {} }, + permissions: { contents: 'read' }, + jobs: { + contract: { + 'runs-on': 'ubuntu-24.04', + steps: [ + { uses: 'actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5' }, + { + name: 'Test contract guard', + run: command({ file: 'python3', args: ['scripts/test-contract.py'] }), + }, + { + name: 'Verify pinned public operations', + run: command({ file: 'python3', args: ['scripts/check-contract.py'] }), + }, + ], + }, + }, +}); diff --git a/generation-provenance.json b/generation-provenance.json new file mode 100644 index 0000000..0d44c1f --- /dev/null +++ b/generation-provenance.json @@ -0,0 +1,12 @@ +{ + "source_spec_sha": "9f8d54f123e81b8bc7252f855c52ecbf7cc8ae42", + "source_spec_sha256": "c0b2db893e3017c5c83c14375e6085581584641f617ee7ea1305ab80e9b50421", + "generator_version": "0.38.0", + "build_version": "0.1.16", + "configuration_sha256": "10d2f59b8a69dce627060e1104eac425cec104dd90d3177c08a29a902cb48875", + "operation_count": 31, + "generated_commit": "bc3e12c4dd8d4d0557b5e2847049a2ecc7df21df", + "download_sha256": null, + "integration_base": "scalar-next", + "published_package": false +} diff --git a/pyproject.toml b/pyproject.toml index f4cfded..b52941d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "dedalus-sdk" -version = "0.1.0" # x-release-please-version +version = "0.6.0" # x-release-please-version description = "Create, run, and manage Dedalus Machines." readme = "README.md" license = "Apache-2.0" diff --git a/scripts/check-contract.py b/scripts/check-contract.py new file mode 100644 index 0000000..0e1b4b5 --- /dev/null +++ b/scripts/check-contract.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Compare generated operations with the independently pinned public API contract.""" + +import json +from collections import Counter +from pathlib import Path + + +def check(contract, manifest): + expected = {(op["method"], op["path"]): op for op in contract["operations"]} + counts = Counter((op["method"].upper(), op["path"]) for op in manifest["operations"]) + errors = [] + for key in sorted(expected.keys() - counts.keys()): + errors.append(f"missing operation: {key}") + for key in sorted(counts.keys() - expected.keys()): + errors.append(f"obsolete operation: {key}") + for key, count in counts.items(): + if count != 1: + errors.append(f"duplicate operation: {key}") + for op in manifest["operations"]: + key = (op["method"].upper(), op["path"]) + if key in expected and sorted(op.get("bodyParams", [])) != expected[key]["bodyParams"]: + errors.append(f"request fields differ: {key}") + return errors + + +if __name__ == "__main__": + root = Path(__file__).resolve().parents[1] + contract = json.loads((root / "api-contract.json").read_text()) + manifest = json.loads((root / "scalar-sdk.manifest.json").read_text()) + errors = check(contract, manifest) + if errors: + raise SystemExit("\n".join(errors)) + print(f"Contract verified: {len(contract['operations'])} operations; source {contract['source_sha']}") diff --git a/scripts/test-contract.py b/scripts/test-contract.py new file mode 100644 index 0000000..4e50569 --- /dev/null +++ b/scripts/test-contract.py @@ -0,0 +1,36 @@ +"""Mutation tests: stale output must never satisfy the pinned contract.""" + +import copy +import json +import runpy +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +check = runpy.run_path(str(ROOT / "scripts/check-contract.py"))["check"] + + +class ContractGuardTests(unittest.TestCase): + def test_rejects_missing_obsolete_duplicate_and_changed_fields(self): + contract = json.loads((ROOT / "api-contract.json").read_text()) + manifest = json.loads((ROOT / "scalar-sdk.manifest.json").read_text()) + self.assertEqual(check(contract, manifest), []) + for mode in ("missing", "obsolete", "duplicate", "field"): + with self.subTest(mode=mode): + changed = copy.deepcopy(manifest) + operations = changed["operations"] + if mode == "missing": + operations.pop() + elif mode == "obsolete": + operations[0]["method"] = "TRACE" + elif mode == "duplicate": + operations.append(operations[0]) + else: + next(op for op in operations if op["method"] == "POST" and op["path"] == "/v1/machines")[ + "bodyParams" + ].remove("image_id") + self.assertTrue(check(contract, changed)) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/dedalus_sdk/images.py b/src/dedalus_sdk/images.py new file mode 100644 index 0000000..0872a06 --- /dev/null +++ b/src/dedalus_sdk/images.py @@ -0,0 +1,326 @@ +"""Image import workflows using the SDK transport and a separate signed-upload client.""" + +from __future__ import annotations + +import base64 +import hashlib +import math +import os +import stat +import time +from datetime import datetime, timezone +from typing import BinaryIO, Callable, Literal, Optional, Union, cast +from urllib.parse import parse_qs, quote, urlsplit +from uuid import uuid4 + +import anyio +import httpx +from typing_extensions import TypedDict + +from . import APITimeoutError, AsyncDedalus, Dedalus + + +class Image(TypedDict): + image_id: str + state: str + + +class ImagePreparationError(RuntimeError): + def __init__(self, image: Image, message: str) -> None: + self.image = image + super().__init__(f"Image {image['image_id']}: {message}") + + +def _record(value: object) -> dict[str, object]: + if not isinstance(value, dict): + raise ValueError("Invalid image API response") + return cast("dict[str, object]", value) + + +def _image(value: object, expected: Optional[str] = None) -> Image: + result = _record(value) + if ( + not isinstance(result.get("image_id"), str) + or not result["image_id"] + or not isinstance(result.get("state"), str) + or not result["state"] + or (expected is not None and result["image_id"] != expected) + ): + raise ValueError("Invalid or mismatched image API response") + return cast(Image, result) + + +def _ready(image: Image, progress: Optional[Callable[[Image], None]]) -> bool: + if progress: + progress(image) + if image["state"] in ("failed", "rejected", "revoked"): + details = _record(image) + error = _record(details.get("error") or {}) + message = error.get("message") or details.get("reason") or image["state"] + code = f"{error['error_code']}: " if error.get("error_code") else "" + raise ImagePreparationError(image, f"{code}{message}") + return image["state"] == "ready" + + +def _duration(value: float, name: str) -> float: + if not math.isfinite(value) or not 0 < value <= 86400: + raise ValueError(f"{name} must be between 0 and 86400 seconds") + return value + + +def _remaining(end: float, image: Optional[Image] = None) -> float: + remaining = end - time.monotonic() + if remaining <= 0: + if image is not None: + raise ImagePreparationError( + image, "Timed out waiting. Preparation continues; use this image ID to resume polling." + ) + raise TimeoutError("Image import timed out before receiving an image ID") + return remaining + + +def _identity(image: Union[str, Image]) -> str: + value = image if isinstance(image, str) else image["image_id"] + if not value or any(char.isspace() for char in value): + raise ValueError("image ID must be a nonempty string without whitespace") + return value + + +def poll_image( + client: Dedalus, + image: Union[str, Image], + *, + timeout: float = 3600, + poll_interval: float = 2, + on_progress: Optional[Callable[[Image], None]] = None, +) -> Image: + """Wait for readiness. Timeout stops polling, never server preparation.""" + end = time.monotonic() + _duration(timeout, "timeout") + interval = _duration(poll_interval, "poll_interval") + image_id = _identity(image) + current = None if isinstance(image, str) else _image(image, image_id) + while True: + remaining = _remaining(end, current or Image(image_id=image_id, state="unknown")) + if current is None: + try: + response = client.get( + f"/v1/images/{quote(image_id, safe='')}", + cast_to=httpx.Response, + options={"timeout": remaining, "max_retries": 0}, + ) + except APITimeoutError as error: + raise ImagePreparationError( + Image(image_id=image_id, state="unknown"), + "Status request timed out. Preparation continues; use this image ID to resume polling.", + ) from error + current = _image(response.json(), image_id) + _remaining(end, current) + if _ready(current, on_progress): + return current + time.sleep(min(interval, _remaining(end, current))) + _remaining(end, current) + current = None + + +async def async_poll_image( + client: AsyncDedalus, + image: Union[str, Image], + *, + timeout: float = 3600, + poll_interval: float = 2, + on_progress: Optional[Callable[[Image], None]] = None, +) -> Image: + """Async readiness polling; task cancellation leaves preparation running.""" + image_id = _identity(image) + interval = _duration(poll_interval, "poll_interval") + current = None if isinstance(image, str) else _image(image, image_id) + try: + with anyio.fail_after(_duration(timeout, "timeout")): + while True: + if current is None: + response = await client.get(f"/v1/images/{quote(image_id, safe='')}", cast_to=httpx.Response) + current = _image(response.json(), image_id) + if _ready(current, on_progress): + return current + await anyio.sleep(interval) + current = None + except (TimeoutError, APITimeoutError) as error: + raise ImagePreparationError( + Image(image_id=image_id, state="unknown"), + "Timed out waiting. Preparation continues; use this image ID to resume polling.", + ) from error + + +def _hash(file: BinaryIO, end: float) -> tuple[str, int]: + before = os.fstat(file.fileno()) + if not stat.S_ISREG(before.st_mode) or not 0 < before.st_size <= 5 * 1024**3: + raise ValueError("Image archive must be a regular file between 1 byte and 5 GiB") + digest = hashlib.sha256() + count = 0 + while True: + _remaining(end) + chunk = file.read(1024 * 1024) + if not chunk: + break + digest.update(chunk) + count += len(chunk) + after = os.fstat(file.fileno()) + if count != before.st_size or after.st_size != before.st_size or after.st_mtime_ns != before.st_mtime_ns: + raise ValueError("Image archive changed while hashing") + file.seek(0) + return digest.hexdigest(), count + + +def _capability(value: object, sha256: str, size: int) -> tuple[dict[str, object], str, httpx.Headers]: + reservation = _record(value) + source, upload = _record(reservation.get("source")), _record(reservation.get("upload")) + try: + url = upload["url"] + if not isinstance(url, str) or not isinstance(upload["expires_at"], str): + raise ValueError() + endpoint = urlsplit(url) + expires = datetime.fromisoformat(upload["expires_at"].replace("Z", "+00:00")) + headers = httpx.Headers() + for key, values in _record(upload.get("headers")).items(): + if key.lower() in ("authorization", "proxy-authorization", "cookie") or not isinstance(values, list): + raise ValueError() + if not all(isinstance(value, str) for value in values): + raise ValueError() + headers[key] = ", ".join(values) + checksum = ( + headers.get("x-amz-checksum-sha256") or parse_qs(endpoint.query).get("X-Amz-Checksum-Sha256", [""])[0] + ) + if ( + source.get("kind") != "docker_archive" + or source.get("sha256") != sha256 + or not isinstance(source.get("upload_id"), str) + or not source["upload_id"] + or upload.get("method") != "PUT" + or endpoint.scheme != "https" + or not endpoint.hostname + or endpoint.username + or endpoint.password + or endpoint.fragment + or expires <= datetime.now(timezone.utc) + or headers.get("content-length") != str(size) + or headers.get("if-none-match") != "*" + or checksum != base64.b64encode(bytes.fromhex(sha256)).decode() + ): + raise ValueError() + return source, url, headers + except (KeyError, ValueError, TypeError): + raise ValueError("Invalid image upload capability") from None + + +def _uploaded(response: httpx.Response) -> None: + # Registration verifies an existing immutable object after a repeated PUT. + if not response.is_success and response.status_code != 412: + raise RuntimeError(f"Image archive upload failed: HTTP {response.status_code}") + + +def import_image( + client: Dedalus, + path: Union[str, os.PathLike[str]], + *, + wait: bool = True, + name: Optional[str] = None, + platform: Literal["linux/amd64"] = "linux/amd64", + timeout: float = 3600, + poll_interval: float = 2, + idempotency_key: Optional[str] = None, + on_progress: Optional[Callable[[Image], None]] = None, + upload_transport: Optional[httpx.BaseTransport] = None, +) -> Image: + """Stream a docker-save archive, register it, and wait by default. + + The sync deadline is checked between I/O operations; each request has a + remaining-budget inactivity timeout and automatic API retries are disabled. + """ + if platform != "linux/amd64": + raise ValueError("Custom images currently require linux/amd64") + end = time.monotonic() + _duration(timeout, "timeout") + _duration(poll_interval, "poll_interval") + key = idempotency_key or str(uuid4()) + with open(path, "rb") as file: + sha256, size = _hash(file, end) + response = client.post( + "/v1/images/uploads", + cast_to=httpx.Response, + body={"sha256": sha256, "size_bytes": size, "platform": platform}, + options={"idempotency_key": key, "timeout": _remaining(end), "max_retries": 0}, + ) + source, url, headers = _capability(response.json(), sha256, size) + with httpx.Client(transport=upload_transport, follow_redirects=False) as storage: + _uploaded(storage.put(url, content=file, headers=headers, timeout=_remaining(end))) + response = client.post( + "/v1/images", + cast_to=httpx.Response, + body={"source": source, "platform": platform, **({"name": name} if name is not None else {})}, + options={"idempotency_key": key, "timeout": _remaining(end), "max_retries": 0}, + ) + image = _image(response.json()) + if not wait: + _ready(image, on_progress) + return image + return poll_image( + client, image, timeout=_remaining(end, image), poll_interval=poll_interval, on_progress=on_progress + ) + + +async def async_import_image( + client: AsyncDedalus, + path: Union[str, os.PathLike[str]], + *, + wait: bool = True, + name: Optional[str] = None, + platform: Literal["linux/amd64"] = "linux/amd64", + timeout: float = 3600, + poll_interval: float = 2, + idempotency_key: Optional[str] = None, + on_progress: Optional[Callable[[Image], None]] = None, + upload_transport: Optional[httpx.AsyncBaseTransport] = None, +) -> Image: + """Async import with automatic waiting; cancellation never deletes an image.""" + if platform != "linux/amd64": + raise ValueError("Custom images currently require linux/amd64") + end = time.monotonic() + _duration(timeout, "timeout") + _duration(poll_interval, "poll_interval") + key = idempotency_key or str(uuid4()) + image = None + try: + with anyio.fail_after(timeout): + with open(path, "rb") as file: + sha256, size = await anyio.to_thread.run_sync(_hash, file, end) + response = await client.post( + "/v1/images/uploads", + cast_to=httpx.Response, + body={"sha256": sha256, "size_bytes": size, "platform": platform}, + options={"idempotency_key": key}, + ) + source, url, headers = _capability(response.json(), sha256, size) + + async def chunks(): + while True: + chunk = await anyio.to_thread.run_sync(file.read, 1024 * 1024) + if not chunk: + break + yield chunk + + async with httpx.AsyncClient(transport=upload_transport, follow_redirects=False) as storage: + _uploaded(await storage.put(url, content=chunks(), headers=headers, timeout=_remaining(end))) + response = await client.post( + "/v1/images", + cast_to=httpx.Response, + body={"source": source, "platform": platform, **({"name": name} if name is not None else {})}, + options={"idempotency_key": key}, + ) + image = _image(response.json()) + if not wait: + _ready(image, on_progress) + return image + return await async_poll_image( + client, image, timeout=_remaining(end, image), poll_interval=poll_interval, on_progress=on_progress + ) + except TimeoutError: + _remaining(end, image) + raise diff --git a/tests/test_images.py b/tests/test_images.py new file mode 100644 index 0000000..b4aa2d0 --- /dev/null +++ b/tests/test_images.py @@ -0,0 +1,310 @@ +from __future__ import annotations + +import base64 +import hashlib +import json + +import httpx +import pytest + +from dedalus_sdk import APITimeoutError, AsyncDedalus, Dedalus +from dedalus_sdk.images import ImagePreparationError, async_import_image, async_poll_image, import_image, poll_image + +IMAGE_ID = "01994a10-1234-7000-8000-000000000001" +ARCHIVE = b"fixture docker-save archive" +DIGEST = hashlib.sha256(ARCHIVE).hexdigest() + + +def fixture(states=None, mutate=lambda grant: None, upload_status=200): + requests, uploads, keys = [], [], [] + states = iter(states or ["ready"]) + grant = { + "source": {"kind": "docker_archive", "upload_id": IMAGE_ID, "sha256": DIGEST}, + "upload": { + "url": "https://storage.example/image?signature=secret", + "method": "PUT", + "expires_at": "2099-01-01T00:00:00Z", + "headers": { + "content-length": [str(len(ARCHIVE))], + "if-none-match": ["*"], + "x-amz-checksum-sha256": [base64.b64encode(bytes.fromhex(DIGEST)).decode()], + }, + }, + } + mutate(grant) + + def api(request): + requests.append(request.url.path) + assert "fixture-secret" in request.headers["authorization"] + if request.method == "POST": + keys.append(request.headers["idempotency-key"]) + if request.url.path.endswith("/uploads"): + assert json.loads(request.content)["sha256"] == DIGEST + return httpx.Response(200, json=grant) + if request.url.path == "/v1/machines": + assert json.loads(request.content)["image_id"] == IMAGE_ID + return httpx.Response( + 200, + json={ + "machine_id": "fixture", + "lifecycle_status": { + "autoresize": { + "cpu": {"blocked_reason": "MACHINE_QUOTA_EXCEEDED", "blocked_at": "2026-01-01T00:00:00Z"}, + "memory": None, + } + }, + }, + ) + state = "submitted" if request.method == "POST" else next(states, "preparing") + return httpx.Response(202 if request.method == "POST" else 200, json={"image_id": IMAGE_ID, "state": state}) + + def storage(request): + uploads.append(request) + assert "authorization" not in request.headers + assert request.content == ARCHIVE + return httpx.Response(upload_status) + + return httpx.MockTransport(api), httpx.MockTransport(storage), requests, uploads, keys + + +@pytest.fixture +def archive(tmp_path): + path = tmp_path / "image.tar" + path.write_bytes(ARCHIVE) + return path + + +@pytest.mark.parametrize("wait", [True, False]) +def test_import_sync(archive, wait): + api, storage, requests, uploads, keys = fixture(["preparing", "ready"]) + progress = [] + with Dedalus(api_key="fixture-secret", http_client=httpx.Client(transport=api)) as client: + result = import_image( + client, + archive, + wait=wait, + poll_interval=0.001, + upload_transport=storage, + on_progress=lambda image: progress.append(image["state"]), + ) + assert result["state"] == ("ready" if wait else "submitted") + assert progress == (["submitted", "preparing", "ready"] if wait else ["submitted"]) + assert len(uploads) == 1 and keys[0] == keys[1] + assert len(requests) == (4 if wait else 2) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("wait", [True, False]) +async def test_import_async(archive, wait): + api, storage, requests, uploads, keys = fixture(["preparing", "ready"]) + async with AsyncDedalus(api_key="fixture-secret", http_client=httpx.AsyncClient(transport=api)) as client: + result = await async_import_image(client, archive, wait=wait, poll_interval=0.001, upload_transport=storage) + assert result["state"] == ("ready" if wait else "submitted") + assert len(uploads) == 1 and keys[0] == keys[1] + assert len(requests) == (4 if wait else 2) + + +@pytest.mark.parametrize( + "change", + [ + lambda g: g["upload"].update(url="http://storage.example/x"), + lambda g: g["upload"].update(method="POST"), + lambda g: g["upload"].update(expires_at="invalid"), + lambda g: g["source"].update(sha256="wrong"), + lambda g: g["upload"]["headers"].update(authorization=["secret"]), + lambda g: g["upload"]["headers"].update({"content-length": ["1"]}), + ], +) +def test_invalid_capability_never_uploads_or_registers(archive, change): + api, storage, requests, uploads, _ = fixture(mutate=change) + with Dedalus(api_key="fixture-secret", http_client=httpx.Client(transport=api)) as client: + with pytest.raises(ValueError, match="Invalid image upload"): + import_image(client, archive, upload_transport=storage) + assert len(requests) == 1 and not uploads + + +@pytest.mark.parametrize("state", ["failed", "rejected", "revoked"]) +def test_failure_preserves_image_id(state): + api, _, requests, _, _ = fixture([state]) + with Dedalus(api_key="fixture-secret", http_client=httpx.Client(transport=api)) as client: + with pytest.raises(ImagePreparationError, match=state) as error: + poll_image(client, IMAGE_ID) + assert error.value.image["image_id"] == IMAGE_ID + assert requests == [f"/v1/images/{IMAGE_ID}"] + + +def test_sync_status_request_timeout_preserves_accepted_image(archive): + api, storage, requests, _, _ = fixture() + timeout = httpx.ReadTimeout("status response timed out") + + def handle(request): + if request.method == "GET": + timeout.request = request + raise timeout + return api.handle_request(request) + + with ( + Dedalus(api_key="fixture-secret", http_client=httpx.Client(transport=httpx.MockTransport(handle))) as client, + pytest.raises(ImagePreparationError, match="Preparation continues.*resume polling") as error, + ): + import_image(client, archive, poll_interval=0.001, upload_transport=storage) + + assert requests == ["/v1/images/uploads", "/v1/images"] + assert error.value.image == {"image_id": IMAGE_ID, "state": "unknown"} + assert IMAGE_ID in str(error.value) + assert isinstance(error.value.__cause__, APITimeoutError) + assert error.value.__cause__.__cause__ is timeout + assert timeout.request.url.path == f"/v1/images/{IMAGE_ID}" + + +@pytest.mark.asyncio +async def test_async_status_request_timeout_preserves_accepted_image(archive): + api, storage, requests, _, _ = fixture() + timeout = httpx.ReadTimeout("status response timed out") + + async def handle(request): + if request.method == "GET": + timeout.request = request + raise timeout + return await api.handle_async_request(request) + + async with AsyncDedalus( + api_key="fixture-secret", max_retries=0, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handle)) + ) as client: + with pytest.raises(ImagePreparationError, match="Preparation continues.*resume polling") as error: + await async_import_image(client, archive, poll_interval=0.001, upload_transport=storage) + + assert requests == ["/v1/images/uploads", "/v1/images"] + assert error.value.image == {"image_id": IMAGE_ID, "state": "unknown"} + assert IMAGE_ID in str(error.value) + assert isinstance(error.value.__cause__, APITimeoutError) + assert error.value.__cause__.__cause__ is timeout + assert timeout.request.url.path == f"/v1/images/{IMAGE_ID}" + + +@pytest.mark.asyncio +async def test_async_failure_timeout_and_cancellation(): + import asyncio + + api, _, requests, _, _ = fixture(["failed"]) + async with AsyncDedalus(api_key="fixture-secret", http_client=httpx.AsyncClient(transport=api)) as client: + with pytest.raises(ImagePreparationError, match="failed"): + await async_poll_image(client, IMAGE_ID) + with pytest.raises(ImagePreparationError, match="Preparation continues") as error: + await async_poll_image(client, IMAGE_ID, timeout=0.02, poll_interval=0.005) + assert error.value.image["image_id"] == IMAGE_ID + assert isinstance(error.value.__cause__, TimeoutError) + task = asyncio.create_task(async_poll_image(client, IMAGE_ID, poll_interval=0.005)) + await asyncio.sleep(0.01) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert all(path == f"/v1/images/{IMAGE_ID}" for path in requests) + + +def test_sync_unknown_states_and_timeout(): + api, _, _, _, _ = fixture(["future-state", "ready"]) + with Dedalus(api_key="fixture-secret", http_client=httpx.Client(transport=api)) as client: + assert poll_image(client, IMAGE_ID, poll_interval=0.001)["state"] == "ready" + with pytest.raises(ImagePreparationError, match="Preparation continues"): + poll_image(client, IMAGE_ID, timeout=0.02, poll_interval=0.005) + + +@pytest.mark.parametrize("status", [302, 500, 412]) +def test_upload_failure_never_registers_but_repeated_put_can(archive, status): + api, storage, requests, _, _ = fixture(upload_status=status) + with Dedalus(api_key="fixture-secret", http_client=httpx.Client(transport=api)) as client: + if status == 412: + assert import_image(client, archive, wait=False, upload_transport=storage)["state"] == "submitted" + else: + with pytest.raises(RuntimeError, match=f"HTTP {status}"): + import_image(client, archive, upload_transport=storage) + assert len(requests) == 1 + + +def test_ready_image_to_generated_machine(archive): + api, storage, requests, _, _ = fixture(["ready"]) + with Dedalus(api_key="fixture-secret", http_client=httpx.Client(transport=api)) as client: + ready = import_image(client, archive, upload_transport=storage, poll_interval=0.001) + machine = client.machines.create(image_id=ready["image_id"]) + assert machine.machine_id == "fixture" + assert requests == ["/v1/images/uploads", "/v1/images", f"/v1/images/{IMAGE_ID}", "/v1/machines"] + + +@pytest.mark.asyncio +async def test_async_ready_image_to_generated_machine(archive): + api, storage, requests, _, _ = fixture(["ready"]) + async with AsyncDedalus(api_key="fixture-secret", http_client=httpx.AsyncClient(transport=api)) as client: + ready = await async_import_image(client, archive, upload_transport=storage, poll_interval=0.001) + machine = await client.machines.create(image_id=ready["image_id"]) + assert machine.machine_id == "fixture" + assert requests[-1] == "/v1/machines" + + +def test_generated_patch_resize_and_flat_errors(): + from dedalus_sdk import APIStatusError + + requests = [] + envelope = { + "error_code": "IMAGE_SOURCE_INVALID", + "message": "archive rejected", + "retryable": False, + "details": {"stage": "validation"}, + "retry_after_ms": 500, + } + + def api(request): + requests.append((request.method, request.url.path)) + return ( + httpx.Response(422, json=envelope) + if "/images/" in request.url.path + else httpx.Response( + 200, + json={ + "status": { + "phase": "running", + "reason": "", + "retryable": False, + "revision": "1", + "last_transition_at": "2026-01-01T00:00:00Z", + "last_progress_at": "2026-01-01T00:00:00Z", + "autoresize": {"cpu": {"blocked_reason": "MACHINE_QUOTA_EXCEEDED"}, "memory": None}, + } + }, + ) + ) + + with Dedalus( + api_key="fixture", max_retries=0, http_client=httpx.Client(transport=httpx.MockTransport(api)) + ) as client: + client.machines.autoresizing.update(machine_id=IMAGE_ID) + client.organization.autoresizing.update() + resized = client.machines.resize(machine_id=IMAGE_ID, vcpu=2) + assert resized.status.autoresize.cpu.blocked_reason == "MACHINE_QUOTA_EXCEEDED" + assert resized.status.autoresize.memory is None + with pytest.raises(APIStatusError) as error: + client.images.retrieve(image_id=IMAGE_ID) + assert error.value.body == envelope + assert "archive rejected" in str(error.value) + assert requests[:3] == [ + ("PATCH", f"/v1/machines/{IMAGE_ID}/autoresizing"), + ("PATCH", "/v1/organization/autoresizing"), + ("POST", f"/v1/machines/{IMAGE_ID}/resize"), + ] + + +def test_unsupported_platform_never_reserves(archive): + api, storage, requests, uploads, _ = fixture() + with Dedalus(api_key="fixture-secret", http_client=httpx.Client(transport=api)) as client: + with pytest.raises(ValueError, match="linux/amd64"): + import_image(client, archive, platform="linux/arm64", upload_transport=storage) + assert not requests and not uploads + + +@pytest.mark.asyncio +async def test_async_unsupported_platform_never_reserves(archive): + api, storage, requests, uploads, _ = fixture() + async with AsyncDedalus(api_key="fixture-secret", http_client=httpx.AsyncClient(transport=api)) as client: + with pytest.raises(ValueError, match="linux/amd64"): + await async_import_image(client, archive, platform="linux/arm64", upload_transport=storage) + assert not requests and not uploads