From 155dd8f56923c9ea5b6f3d737c333c27490678ea Mon Sep 17 00:00:00 2001 From: Shengming Liang <231182611+AgentWings@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:46:16 -0800 Subject: [PATCH 1/2] feat(images): add python import workflows --- .github/workflows/sdk-ci.yml | 2 + README.md | 42 +++++ src/dedalus_sdk/images.py | 316 +++++++++++++++++++++++++++++++++++ tests/test_images.py | 157 +++++++++++++++++ 4 files changed, 517 insertions(+) create mode 100644 src/dedalus_sdk/images.py create mode 100644 tests/test_images.py 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 f33cb30..a94453a 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,47 @@ 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. + ## Usage ```python diff --git a/src/dedalus_sdk/images.py b/src/dedalus_sdk/images.py new file mode 100644 index 0000000..5417868 --- /dev/null +++ b/src/dedalus_sdk/images.py @@ -0,0 +1,316 @@ +"""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 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: + response = client.get( + f"/v1/images/{quote(image_id, safe='')}", + cast_to=httpx.Response, + options={"timeout": remaining, "max_retries": 0}, + ) + 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: + raise ImagePreparationError( + Image(image_id=image_id, state="unknown"), + "Timed out waiting. Preparation continues; use this image ID to resume polling.", + ) from None + + +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/arm64"] = "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. + """ + 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/arm64"] = "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.""" + 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..cbc65a0 --- /dev/null +++ b/tests/test_images.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +import base64 +import hashlib +import json + +import httpx +import pytest + +from dedalus_sdk import AsyncDedalus, Dedalus +from dedalus_sdk.images import async_import_image, async_poll_image, import_image, poll_image, ImagePreparationError + +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) + 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}"] + + +@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"): + await async_poll_image(client, IMAGE_ID, timeout=0.02, poll_interval=0.005) + 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 From 65814a1074df2b18ba4b063a51bc09fa717937b8 Mon Sep 17 00:00:00 2001 From: Simon Liang <231182611+AgentWings@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:45:47 -0800 Subject: [PATCH 2/2] fix(images): retain image identity on request timeout --- src/dedalus_sdk/images.py | 22 +++++++++------ tests/test_images.py | 57 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 68 insertions(+), 11 deletions(-) diff --git a/src/dedalus_sdk/images.py b/src/dedalus_sdk/images.py index c29e2e2..0872a06 100644 --- a/src/dedalus_sdk/images.py +++ b/src/dedalus_sdk/images.py @@ -17,7 +17,7 @@ import httpx from typing_extensions import TypedDict -from . import AsyncDedalus, Dedalus +from . import APITimeoutError, AsyncDedalus, Dedalus class Image(TypedDict): @@ -102,11 +102,17 @@ def poll_image( while True: remaining = _remaining(end, current or Image(image_id=image_id, state="unknown")) if current is None: - response = client.get( - f"/v1/images/{quote(image_id, safe='')}", - cast_to=httpx.Response, - options={"timeout": remaining, "max_retries": 0}, - ) + 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): @@ -138,11 +144,11 @@ async def async_poll_image( return current await anyio.sleep(interval) current = None - except TimeoutError: + 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 None + ) from error def _hash(file: BinaryIO, end: float) -> tuple[str, int]: diff --git a/tests/test_images.py b/tests/test_images.py index 6f68dbd..b4aa2d0 100644 --- a/tests/test_images.py +++ b/tests/test_images.py @@ -7,8 +7,8 @@ import httpx import pytest -from dedalus_sdk import AsyncDedalus, Dedalus -from dedalus_sdk.images import async_import_image, async_poll_image, import_image, poll_image, ImagePreparationError +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" @@ -133,6 +133,55 @@ def test_failure_preserves_image_id(state): 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 @@ -141,8 +190,10 @@ async def test_async_failure_timeout_and_cancellation(): 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"): + 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()