From 48c38a43f627bd3bfa540a3f0b7cf8a637bbd2c6 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 14:50:24 +0500 Subject: [PATCH 01/37] Add HTTPClient and AsyncHTTPClient with dstack defaults --- .../core/backends/vastai/api_client.py | 5 +- .../proxy/gateway/services/server_client.py | 6 +- .../proxy/lib/services/service_connection.py | 3 +- .../server/services/gateways/client.py | 3 +- .../services/jobs/job_replica_http_client.py | 3 +- .../server/services/jobs/server_connection.py | 3 +- .../server/services/logs/fluentbit.py | 3 +- src/dstack/_internal/utils/http.py | 90 +++++++++++++++++++ .../server/services/logs/test_fluentbit.py | 2 +- src/tests/_internal/utils/test_http.py | 67 ++++++++++++++ 10 files changed, 174 insertions(+), 11 deletions(-) create mode 100644 src/dstack/_internal/utils/http.py create mode 100644 src/tests/_internal/utils/test_http.py diff --git a/src/dstack/_internal/core/backends/vastai/api_client.py b/src/dstack/_internal/core/backends/vastai/api_client.py index c3015ed28..bab0eaf07 100644 --- a/src/dstack/_internal/core/backends/vastai/api_client.py +++ b/src/dstack/_internal/core/backends/vastai/api_client.py @@ -7,7 +7,7 @@ from dstack._internal.core.consts import DSTACK_RUNNER_SSH_PORT from dstack._internal.core.errors import ComputeError from dstack._internal.core.models.common import RegistryAuth -from dstack._internal.utils.tls import get_default_ssl_context +from dstack._internal.utils.http import HTTPClient class VastAIRateLimitError(Exception): @@ -33,11 +33,10 @@ def __init__( class VastAIAPIClient: def __init__(self, api_key: str): - self.s = httpx2.Client( + self.s = HTTPClient( base_url="https://console.vast.ai/api/", headers={"Authorization": f"Bearer {api_key}"}, timeout=30, - verify=get_default_ssl_context(), ) def create_instance( diff --git a/src/dstack/_internal/proxy/gateway/services/server_client.py b/src/dstack/_internal/proxy/gateway/services/server_client.py index 4e6979a01..ad21e8e7a 100644 --- a/src/dstack/_internal/proxy/gateway/services/server_client.py +++ b/src/dstack/_internal/proxy/gateway/services/server_client.py @@ -7,6 +7,8 @@ import httpx2 +from dstack._internal.utils.http import AsyncHTTPClient + logger = logging.getLogger(__name__) BASE_URL = "http://dstack/" # any hostname will work @@ -26,7 +28,7 @@ def seems_disconnected(self) -> bool: return self.connect_errors[-1] - self.connect_errors[0] >= datetime.timedelta(minutes=2) -class HTTPMultiClient(httpx2.AsyncClient): +class HTTPMultiClient(AsyncHTTPClient): """Gateway HTTP client for uncached project-access checks against dstack-server. GatewayProxyAuthProvider uses this client and owns authorization decisions and @@ -85,7 +87,7 @@ def _iter_clients_rand(self) -> Generator[CachedClientInfo, None, None]: @staticmethod def _make_client(socket: Path) -> CachedClientInfo: - client = httpx2.AsyncClient( + client = AsyncHTTPClient( transport=httpx2.AsyncHTTPTransport(uds=str(socket.absolute())), base_url=BASE_URL, ) diff --git a/src/dstack/_internal/proxy/lib/services/service_connection.py b/src/dstack/_internal/proxy/lib/services/service_connection.py index 96b71b501..829feabf9 100644 --- a/src/dstack/_internal/proxy/lib/services/service_connection.py +++ b/src/dstack/_internal/proxy/lib/services/service_connection.py @@ -19,6 +19,7 @@ from dstack._internal.proxy.lib.models import Project, Replica, Service from dstack._internal.proxy.lib.repo import BaseProxyRepo from dstack._internal.utils.common import get_or_error, run_async +from dstack._internal.utils.http import AsyncHTTPClient from dstack._internal.utils.logging import get_logger from dstack._internal.utils.path import FileContent @@ -36,7 +37,7 @@ REPLICA_DRAIN_TIMEOUT = 300 -class ServiceClient(httpx2.AsyncClient): +class ServiceClient(AsyncHTTPClient): """ The client that the requests to a service share. """ diff --git a/src/dstack/_internal/server/services/gateways/client.py b/src/dstack/_internal/server/services/gateways/client.py index f6570eaef..2213dcdfa 100644 --- a/src/dstack/_internal/server/services/gateways/client.py +++ b/src/dstack/_internal/server/services/gateways/client.py @@ -28,6 +28,7 @@ from dstack._internal.proxy.gateway.schemas.services import ServiceListItem, ServiceListResponse from dstack._internal.proxy.gateway.schemas.state import StateSummaryResponse from dstack._internal.proxy.gateway.schemas.stats import ServiceStats +from dstack._internal.utils.http import AsyncHTTPClient class GatewayClient: @@ -321,7 +322,7 @@ def gateway_error(data: dict) -> GatewayError: return GatewayError(msg=data["detail"]) -class AsyncClientWrapper(httpx2.AsyncClient): +class AsyncClientWrapper(AsyncHTTPClient): def __del__(self): try: asyncio.get_running_loop().create_task(self.aclose()) diff --git a/src/dstack/_internal/server/services/jobs/job_replica_http_client.py b/src/dstack/_internal/server/services/jobs/job_replica_http_client.py index eebe97887..30e3327b2 100644 --- a/src/dstack/_internal/server/services/jobs/job_replica_http_client.py +++ b/src/dstack/_internal/server/services/jobs/job_replica_http_client.py @@ -8,13 +8,14 @@ from dstack._internal.server.models import JobModel from dstack._internal.server.services.jobs.job_replica_tunnel import get_service_replica_tunnel +from dstack._internal.utils.http import AsyncHTTPClient @asynccontextmanager async def get_service_replica_http_client_over_uds( uds_path: Path, ) -> AsyncGenerator[AsyncClient, None]: - async with AsyncClient(transport=AsyncHTTPTransport(uds=str(uds_path))) as client: + async with AsyncHTTPClient(transport=AsyncHTTPTransport(uds=str(uds_path))) as client: yield client diff --git a/src/dstack/_internal/server/services/jobs/server_connection.py b/src/dstack/_internal/server/services/jobs/server_connection.py index 10646979b..798c85c1d 100644 --- a/src/dstack/_internal/server/services/jobs/server_connection.py +++ b/src/dstack/_internal/server/services/jobs/server_connection.py @@ -22,6 +22,7 @@ from dstack._internal.server import settings from dstack._internal.server.models import JobModel from dstack._internal.server.services.ssh import get_container_ssh_credentials +from dstack._internal.utils.http import AsyncHTTPClient from dstack._internal.utils.logging import get_logger from dstack._internal.utils.path import make_tmp_symlink_to_dir @@ -154,7 +155,7 @@ async def close(self) -> None: async def _server_is_reachable(self) -> bool: transport = httpx2.AsyncHTTPTransport(uds=str(self._probe_socket_path)) try: - async with httpx2.AsyncClient( + async with AsyncHTTPClient( transport=transport, timeout=_PROBE_TIMEOUT, ) as client: diff --git a/src/dstack/_internal/server/services/logs/fluentbit.py b/src/dstack/_internal/server/services/logs/fluentbit.py index ca8850ef5..438e2f827 100644 --- a/src/dstack/_internal/server/services/logs/fluentbit.py +++ b/src/dstack/_internal/server/services/logs/fluentbit.py @@ -19,6 +19,7 @@ unix_time_ms_to_datetime, ) from dstack._internal.utils.common import batched, parse_datetime +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) @@ -163,7 +164,7 @@ class HTTPFluentBitWriter: def __init__(self, host: str, port: int, tag_prefix: str) -> None: self._endpoint = f"http://{host}:{port}" - self._client = httpx2.Client(timeout=30.0) + self._client = HTTPClient(timeout=30.0) self._tag_prefix = tag_prefix def write(self, tag: str, records: List[dict]) -> None: diff --git a/src/dstack/_internal/utils/http.py b/src/dstack/_internal/utils/http.py new file mode 100644 index 000000000..bd8958d0c --- /dev/null +++ b/src/dstack/_internal/utils/http.py @@ -0,0 +1,90 @@ +import ssl +from collections.abc import Mapping +from typing import Optional, Union + +import httpx2 + +from dstack import version +from dstack._internal.utils.tls import get_default_ssl_context + +USER_AGENT = f"dstack/{version.__version__}" + +# The httpx2 defaults. +_DEFAULT_TIMEOUT = httpx2.Timeout(5.0) +_DEFAULT_LIMITS = httpx2.Limits(max_connections=100, max_keepalive_connections=20) + + +class HTTPClient(httpx2.Client): + """ + The base class for dstack's sync HTTP clients: an `httpx2.Client` with dstack defaults. + + `verify=True` trusts the system CA certificates, or the certifi bundle on systems without + them (see `get_default_ssl_context()`). Requests send `User-Agent: dstack/` unless + `headers` set another one. Other defaults are httpx2's: a 5s timeout and no redirects. + """ + + def __init__( + self, + *, + base_url: str = "", + headers: Optional[Mapping[str, str]] = None, + timeout: Union[httpx2.Timeout, float, None] = _DEFAULT_TIMEOUT, + verify: Union[ssl.SSLContext, bool] = True, + follow_redirects: bool = False, + limits: httpx2.Limits = _DEFAULT_LIMITS, + transport: Optional[httpx2.BaseTransport] = None, + ) -> None: + super().__init__( + base_url=base_url, + headers=_get_headers(headers), + timeout=timeout, + verify=_get_verify(verify, transport), + follow_redirects=follow_redirects, + limits=limits, + transport=transport, + ) + + +class AsyncHTTPClient(httpx2.AsyncClient): + """ + The base class for dstack's async HTTP clients: an `httpx2.AsyncClient` with the same + defaults as `HTTPClient`. + """ + + def __init__( + self, + *, + base_url: str = "", + headers: Optional[Mapping[str, str]] = None, + timeout: Union[httpx2.Timeout, float, None] = _DEFAULT_TIMEOUT, + verify: Union[ssl.SSLContext, bool] = True, + follow_redirects: bool = False, + limits: httpx2.Limits = _DEFAULT_LIMITS, + transport: Optional[httpx2.AsyncBaseTransport] = None, + ) -> None: + super().__init__( + base_url=base_url, + headers=_get_headers(headers), + timeout=timeout, + verify=_get_verify(verify, transport), + follow_redirects=follow_redirects, + limits=limits, + transport=transport, + ) + + +def _get_headers(headers: Optional[Mapping[str, str]]) -> httpx2.Headers: + result = httpx2.Headers({"User-Agent": USER_AGENT}) + if headers is not None: + result.update(headers) # case-insensitive, so a caller's user-agent replaces ours + return result + + +def _get_verify( + verify: Union[ssl.SSLContext, bool], + transport: Union[httpx2.BaseTransport, httpx2.AsyncBaseTransport, None], +) -> Union[ssl.SSLContext, bool]: + # httpx2 ignores `verify` when given a transport, so don't build a context for nothing. + if verify is True and transport is None: + return get_default_ssl_context() + return verify diff --git a/src/tests/_internal/server/services/logs/test_fluentbit.py b/src/tests/_internal/server/services/logs/test_fluentbit.py index db8baec94..9517ac92f 100644 --- a/src/tests/_internal/server/services/logs/test_fluentbit.py +++ b/src/tests/_internal/server/services/logs/test_fluentbit.py @@ -46,7 +46,7 @@ class TestHTTPFluentBitWriter: @pytest.fixture def mock_httpx_client(self): - with patch("dstack._internal.server.services.logs.fluentbit.httpx2.Client") as mock: + with patch("dstack._internal.server.services.logs.fluentbit.HTTPClient") as mock: yield mock.return_value def test_init_creates_client(self, mock_httpx_client): diff --git a/src/tests/_internal/utils/test_http.py b/src/tests/_internal/utils/test_http.py new file mode 100644 index 000000000..b96291ae3 --- /dev/null +++ b/src/tests/_internal/utils/test_http.py @@ -0,0 +1,67 @@ +import ssl +from typing import Union + +import httpx2 +import pytest + +from dstack._internal.utils import http +from dstack._internal.utils.http import USER_AGENT, AsyncHTTPClient, HTTPClient + + +class TestHTTPClient: + def test_sends_dstack_user_agent(self): + transport = httpx2.MockTransport(_echo_user_agent) + with HTTPClient(transport=transport) as client: + assert client.get("http://test/").text == USER_AGENT + + def test_keeps_user_agent_from_headers(self): + transport = httpx2.MockTransport(_echo_user_agent) + with HTTPClient(transport=transport, headers={"user-agent": "custom"}) as client: + assert client.get("http://test/").text == "custom" + + def test_uses_default_ssl_context(self, monkeypatch: pytest.MonkeyPatch): + ctx = ssl.create_default_context() + monkeypatch.setattr(http, "get_default_ssl_context", lambda: ctx) + assert _get_ssl_context(HTTPClient()) is ctx + + @pytest.mark.parametrize("verify", [False, ssl.create_default_context()]) + def test_keeps_explicit_verify( + self, monkeypatch: pytest.MonkeyPatch, verify: Union[ssl.SSLContext, bool] + ): + monkeypatch.setattr(http, "get_default_ssl_context", _fail) + ctx = _get_ssl_context(HTTPClient(verify=verify)) + if isinstance(verify, ssl.SSLContext): + assert ctx is verify + else: + assert ctx.verify_mode == ssl.CERT_NONE + + def test_does_not_build_ssl_context_with_transport(self, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(http, "get_default_ssl_context", _fail) + HTTPClient(transport=httpx2.MockTransport(_echo_user_agent)) + + +class TestAsyncHTTPClient: + @pytest.mark.asyncio + async def test_sends_dstack_user_agent(self): + async def handler(request: httpx2.Request) -> httpx2.Response: + return _echo_user_agent(request) + + async with AsyncHTTPClient(transport=httpx2.MockTransport(handler)) as client: + assert (await client.get("http://test/")).text == USER_AGENT + + def test_uses_default_ssl_context(self, monkeypatch: pytest.MonkeyPatch): + ctx = ssl.create_default_context() + monkeypatch.setattr(http, "get_default_ssl_context", lambda: ctx) + assert _get_ssl_context(AsyncHTTPClient()) is ctx + + +def _echo_user_agent(request: httpx2.Request) -> httpx2.Response: + return httpx2.Response(200, text=request.headers["User-Agent"]) + + +def _fail() -> ssl.SSLContext: + raise AssertionError("unexpected call") + + +def _get_ssl_context(client: Union[httpx2.Client, httpx2.AsyncClient]) -> ssl.SSLContext: + return client._transport._pool._ssl_context # type: ignore[attr-defined] From 4f174983fdd13bd491aebcde3daa531219f89f0c Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:18:57 +0500 Subject: [PATCH 02/37] Add http_mock fixture for httpx2 clients --- src/tests/conftest.py | 9 ++ src/tests/http_mock.py | 163 ++++++++++++++++++++++++++++++++++++ src/tests/test_http_mock.py | 53 ++++++++++++ 3 files changed, 225 insertions(+) create mode 100644 src/tests/http_mock.py create mode 100644 src/tests/test_http_mock.py diff --git a/src/tests/conftest.py b/src/tests/conftest.py index 12ab356ac..af3c35924 100644 --- a/src/tests/conftest.py +++ b/src/tests/conftest.py @@ -14,6 +14,7 @@ from dstack._internal.settings import FeatureFlags from dstack._internal.utils import crypto from dstack._internal.utils import ssh as ssh_utils +from tests.http_mock import HTTPMock def pytest_configure(config): @@ -113,3 +114,11 @@ def disable_feature_flags(): if not isinstance(value, bool): raise RuntimeError(f"FeatureFlags.{name}: only bool values are supported") setattr(FeatureFlags, name, False) + + +@pytest.fixture +def http_mock(monkeypatch: pytest.MonkeyPatch) -> HTTPMock: + """Mocks the responses of httpx2 clients. See `HTTPMock`.""" + mock = HTTPMock() + mock.install(monkeypatch) + return mock diff --git a/src/tests/http_mock.py b/src/tests/http_mock.py new file mode 100644 index 000000000..210cbf034 --- /dev/null +++ b/src/tests/http_mock.py @@ -0,0 +1,163 @@ +import json +from typing import Any, Optional, Union +from urllib.parse import parse_qs + +import httpx2 +import pytest + +ResponseSpec = dict[str, Any] +""" +`HTTPMock.register()` keyword arguments for one response: `status_code` (200 if not set), +`json`, `text`, `content`, `headers`, or `exc` to raise an exception instead of responding. +""" + + +class RecordedRequest: + """A request that a mocked transport received.""" + + def __init__(self, request: httpx2.Request) -> None: + request.read() + self.request = request + + @property + def method(self) -> str: + return self.request.method + + @property + def url(self) -> httpx2.URL: + return self.request.url + + @property + def headers(self) -> httpx2.Headers: + return self.request.headers + + @property + def content(self) -> bytes: + return self.request.content + + @property + def qs(self) -> dict[str, list[str]]: + return parse_qs(self.request.url.query.decode()) + + @property + def timeout(self) -> dict[str, Optional[float]]: + """The `connect`, `read`, `write`, and `pool` timeouts.""" + return self.request.extensions["timeout"] + + def json(self) -> Any: + return json.loads(self.request.content) + + +class HTTPMock: + """ + Mocks the responses of all httpx2 clients that use the default transports, including + Unix socket transports. Requests that match no registered URL fail the test. + + A registered URL matches requests with the same method, scheme, host, port, and path + (any path if the registered URL has none), and with at least the registered query + parameters. Later registrations take precedence over earlier ones. + """ + + def __init__(self) -> None: + self._routes: list[_Route] = [] + self.request_history: list[RecordedRequest] = [] + + def install(self, monkeypatch: pytest.MonkeyPatch) -> None: + mock = self + + def handle_request(self: httpx2.HTTPTransport, request: httpx2.Request) -> httpx2.Response: + return mock.handle(request) + + async def handle_async_request( + self: httpx2.AsyncHTTPTransport, request: httpx2.Request + ) -> httpx2.Response: + return mock.handle(request) + + monkeypatch.setattr(httpx2.HTTPTransport, "handle_request", handle_request) + monkeypatch.setattr( + httpx2.AsyncHTTPTransport, "handle_async_request", handle_async_request + ) + + def register( + self, + method: str, + url: str, + response_list: Optional[list[ResponseSpec]] = None, + **response: Any, + ) -> None: + """ + Responds to matching requests with `response`, or with the responses from + `response_list` in turn, repeating the last one when they run out. + """ + if response_list is not None and response: + raise ValueError("Pass either response_list or response arguments, not both") + self._routes.append(_Route(method, httpx2.URL(url), response_list or [response])) + + def get(self, url: str, response_list: Optional[list[ResponseSpec]] = None, **response: Any): + self.register("GET", url, response_list, **response) + + def post(self, url: str, response_list: Optional[list[ResponseSpec]] = None, **response: Any): + self.register("POST", url, response_list, **response) + + def put(self, url: str, response_list: Optional[list[ResponseSpec]] = None, **response: Any): + self.register("PUT", url, response_list, **response) + + def patch(self, url: str, response_list: Optional[list[ResponseSpec]] = None, **response: Any): + self.register("PATCH", url, response_list, **response) + + def delete( + self, url: str, response_list: Optional[list[ResponseSpec]] = None, **response: Any + ): + self.register("DELETE", url, response_list, **response) + + @property + def call_count(self) -> int: + return len(self.request_history) + + @property + def called(self) -> bool: + return bool(self.request_history) + + @property + def last_request(self) -> RecordedRequest: + return self.request_history[-1] + + def handle(self, request: httpx2.Request) -> httpx2.Response: + self.request_history.append(RecordedRequest(request)) + for route in reversed(self._routes): + if route.matches(request): + return route.respond(request) + raise AssertionError(f"No mocked response for {request.method} {request.url}") + + +class _Route: + def __init__(self, method: str, url: httpx2.URL, responses: list[ResponseSpec]) -> None: + self._method = method + self._url = url + self._query = parse_qs(url.query.decode()) + self._responses = responses + self._calls = 0 + + def matches(self, request: httpx2.Request) -> bool: + url = request.url + if ( + request.method != self._method + or url.scheme != self._url.scheme + or url.host != self._url.host + or url.port != self._url.port + ): + return False + if self._url.path not in ("", "/") and url.path != self._url.path: + return False + query = parse_qs(url.query.decode()) + return all(query.get(name) == values for name, values in self._query.items()) + + def respond(self, request: httpx2.Request) -> httpx2.Response: + spec = dict(self._responses[min(self._calls, len(self._responses) - 1)]) + self._calls += 1 + exc: Union[Exception, type[Exception], None] = spec.pop("exc", None) + if isinstance(exc, type): + exc = exc("Mocked error") + if exc is not None: + raise exc + return httpx2.Response(spec.pop("status_code", 200), request=request, **spec) diff --git a/src/tests/test_http_mock.py b/src/tests/test_http_mock.py new file mode 100644 index 000000000..744e5ede1 --- /dev/null +++ b/src/tests/test_http_mock.py @@ -0,0 +1,53 @@ +import httpx2 +import pytest + +from tests.http_mock import HTTPMock + + +class TestHTTPMock: + def test_matches_method_path_and_query_subset(self, http_mock: HTTPMock): + http_mock.get("https://api.test/items?kind=a", json={"kind": "a"}) + http_mock.post("https://api.test/items", status_code=201) + with httpx2.Client() as client: + resp = client.get("https://api.test/items", params={"kind": "a", "page": "2"}) + assert resp.json() == {"kind": "a"} + assert client.post("https://api.test/items", json={"x": 1}).status_code == 201 + assert http_mock.call_count == 2 + assert http_mock.last_request.json() == {"x": 1} + assert http_mock.request_history[0].qs == {"kind": ["a"], "page": ["2"]} + + def test_fails_unmatched_request(self, http_mock: HTTPMock): + http_mock.get("https://api.test/items?kind=a") + with httpx2.Client() as client, pytest.raises(AssertionError, match="No mocked response"): + client.get("https://api.test/items", params={"kind": "b"}) + + def test_later_registration_takes_precedence(self, http_mock: HTTPMock): + http_mock.get("https://api.test/items", text="old") + http_mock.get("https://api.test/items", text="new") + with httpx2.Client() as client: + assert client.get("https://api.test/items").text == "new" + + def test_responds_from_list_and_repeats_last(self, http_mock: HTTPMock): + http_mock.get("https://api.test/items", [{"status_code": 503}, {"json": [1]}]) + with httpx2.Client() as client: + statuses = [client.get("https://api.test/items").status_code for _ in range(3)] + assert statuses == [503, 200, 200] + + @pytest.mark.parametrize("exc", [httpx2.ConnectError, httpx2.ReadTimeout("slow")]) + def test_raises_exc(self, http_mock: HTTPMock, exc): + http_mock.get("https://api.test/items", exc=exc) + with httpx2.Client() as client, pytest.raises(httpx2.TransportError): + client.get("https://api.test/items") + + def test_mocks_unix_socket_transport(self, http_mock: HTTPMock): + http_mock.get("http://localhost/api/healthcheck", json={"ok": True}) + transport = httpx2.HTTPTransport(uds="/nonexistent.sock") + with httpx2.Client(transport=transport, base_url="http://localhost") as client: + assert client.get("/api/healthcheck").json() == {"ok": True} + + @pytest.mark.asyncio + async def test_mocks_async_clients(self, http_mock: HTTPMock): + http_mock.get("https://api.test/items", json=[1]) + async with httpx2.AsyncClient() as client: + assert (await client.get("https://api.test/items")).json() == [1] + assert http_mock.last_request.timeout["read"] == 5.0 From 5e84ca1f1ed45ab6ee1499d0e3d58b11e9c39b49 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:19:03 +0500 Subject: [PATCH 03/37] Move runner and shim clients to httpx2 --- .../pipeline_tasks/instances/check.py | 10 +- .../server/services/jobs/__init__.py | 4 +- .../server/services/runner/client.py | 96 +++--- .../_internal/server/services/runner/ssh.py | 18 +- src/dstack/_internal/server/testing/common.py | 11 +- .../_internal/server/utils/otel/utils.py | 7 +- .../pipeline_tasks/instances/test_check.py | 4 +- .../server/services/runner/test_client.py | 309 +++++++++--------- .../server/services/runner/test_ssh.py | 37 ++- 9 files changed, 257 insertions(+), 239 deletions(-) diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py index 76874b5f6..c8cf9c856 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py @@ -5,8 +5,8 @@ from typing import Optional import gpuhunt +import httpx2 import packaging.version -import requests from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import joinedload @@ -407,7 +407,7 @@ def _check_instance_inner( if check_instance_health: method = shim_client.get_instance_health instance_health_response = method() - except requests.RequestException as exc: + except httpx2.HTTPError as exc: template = "shim.%s(): request error: %s" args = (method.__func__.__name__, exc) logger.debug(template, *args) @@ -448,7 +448,7 @@ def _get_gpu_driver( try: instance_info = shim_client.get_instance_info() return runner_client.instance_info_response_to_gpu_driver(instance_info) - except (requests.RequestException, runner_client.ShimError) as exc: + except (httpx2.HTTPError, runner_client.ShimError) as exc: logger.warning( "Instance %s: shim.get_instance_info(): request error: %s", instance_model.name, exc ) @@ -580,7 +580,7 @@ def _maybe_install_runner( try: shim_client.install_runner(download_url) return True - except requests.RequestException as e: + except httpx2.HTTPError as e: logger.warning("Instance %s: %s: failed to install: %s", instance_model.name, name, e) return False @@ -634,7 +634,7 @@ def _maybe_install_shim( try: shim_client.install_shim(download_url) return True - except requests.RequestException as e: + except httpx2.HTTPError as e: logger.warning("Instance %s: %s: failed to install: %s", instance_model.name, name, e) return False diff --git a/src/dstack/_internal/server/services/jobs/__init__.py b/src/dstack/_internal/server/services/jobs/__init__.py index a9dfc2dfe..f255b7c18 100644 --- a/src/dstack/_internal/server/services/jobs/__init__.py +++ b/src/dstack/_internal/server/services/jobs/__init__.py @@ -4,7 +4,7 @@ from typing import Dict, Iterable, List, Optional, Tuple from uuid import UUID -import requests +import httpx2 from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import load_only @@ -384,7 +384,7 @@ def _stop_runner( except client.RunnerJobSubmissionMismatchError: # The runner the job was submitted to is gone, and this one runs no job of ours to stop logger.debug("%s: runner no longer runs the job, nothing to stop", fmt(job_model)) - except (requests.RequestException, client.RunnerError): + except (httpx2.HTTPError, client.RunnerError): # Stopping the runner is best-effort: the job is being terminated either way. logger.exception("%s: failed to stop runner gracefully", fmt(job_model)) diff --git a/src/dstack/_internal/server/services/runner/client.py b/src/dstack/_internal/server/services/runner/client.py index 10ae8ff13..d1ccf6a87 100644 --- a/src/dstack/_internal/server/services/runner/client.py +++ b/src/dstack/_internal/server/services/runner/client.py @@ -1,15 +1,12 @@ -import urllib.parse import uuid from collections.abc import Generator from http import HTTPStatus from pathlib import Path from typing import BinaryIO, Dict, List, Literal, Optional, Self, TypeVar, Union, overload +import httpx2 import packaging.version import pydantic -import requests -import requests.exceptions -import requests_unixsocket from dstack._internal.core.consts import DSTACK_PROJECT_ENV from dstack._internal.core.errors import DstackError @@ -51,6 +48,7 @@ TaskTerminateRequest, ) from dstack._internal.utils.common import get_or_error +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger from dstack._internal.utils.path import PathLike @@ -85,7 +83,7 @@ class _ResponseError(DstackError): did not get through, repeating the same request is not expected to help. """ - def __init__(self, response: requests.Response) -> None: + def __init__(self, response: httpx2.Response) -> None: super().__init__() self.response = response @@ -102,9 +100,9 @@ def message(self) -> str: @property def _request_line(self) -> str: request = self.response.request - # The full URL is noise: the authority is always localhost or a percent-encoded - # socket path, since the client always talks to a locally forwarded port. - return f"{request.method} {request.path_url}" + # The full URL is noise: the authority is always localhost, since the client always + # talks to a locally forwarded port or socket. + return f"{request.method} {request.url.raw_path.decode()}" @property def _body(self) -> str: @@ -139,7 +137,7 @@ class _ResponseBodyError(_ResponseError): match the expected schema, e.g. because shim or runner is too old or too new. """ - def __init__(self, response: requests.Response, error: pydantic.ValidationError) -> None: + def __init__(self, response: httpx2.Response, error: pydantic.ValidationError) -> None: super().__init__(response) self.error = error @@ -211,7 +209,7 @@ def __init__( hostname: str = "localhost", uds: Optional[PathLike] = None, ): - self._session, self._base_url = _make_session_and_base_url(port, hostname, uds) + self._client = _make_client(port, hostname, uds) @classmethod def from_address(cls, address: LocalAddress) -> Self: @@ -247,15 +245,15 @@ def healthcheck(self) -> Optional[HealthcheckResponse]: """ try: healthcheck_response = self._healthcheck() - except requests.exceptions.RequestException: + except httpx2.HTTPError: return None if not self._negotiated: self._negotiate(healthcheck_response) return healthcheck_response def get_metrics(self, job_submission_id: uuid.UUID) -> Optional[MetricsResponse]: - resp = self._session.get( - self._url("/api/metrics"), + resp = self._client.get( + "/api/metrics", params={"job_submission_id": str(job_submission_id)}, timeout=REQUEST_TIMEOUT, ) @@ -302,30 +300,30 @@ def submit_job( log_quota_hour=quota if quota > 0 else None, run_spec=run.run_spec, ) - resp = self._session.post( - self._url("/api/submit"), - data=body.json_for_runner(), + resp = self._client.post( + "/api/submit", + content=body.json_for_runner(), headers={"Content-Type": "application/json"}, timeout=REQUEST_TIMEOUT, ) self._raise_for_status(resp) def upload_archive(self, id: uuid.UUID, file: Union[BinaryIO, bytes]): - resp = self._session.post( - self._url("/api/upload_archive"), + resp = self._client.post( + "/api/upload_archive", files={"archive": (str(id), file)}, timeout=UPLOAD_CODE_REQUEST_TIMEOUT, ) self._raise_for_status(resp) def upload_code(self, file: Union[BinaryIO, bytes]): - resp = self._session.post( - self._url("/api/upload_code"), data=file, timeout=UPLOAD_CODE_REQUEST_TIMEOUT + resp = self._client.post( + "/api/upload_code", content=file, timeout=UPLOAD_CODE_REQUEST_TIMEOUT ) self._raise_for_status(resp) def run_job(self) -> Optional[JobInfoResponse]: - resp = self._session.post(self._url("/api/run"), timeout=REQUEST_TIMEOUT) + resp = self._client.post("/api/run", timeout=REQUEST_TIMEOUT) self._raise_for_status(resp) if not _is_json_response(resp): # Old runner or runner failed to get job info @@ -333,8 +331,8 @@ def run_job(self) -> Optional[JobInfoResponse]: return self._response(JobInfoResponse, resp) def pull(self, job_submission_id: uuid.UUID, timestamp: int) -> PullResponse: - resp = self._session.get( - self._url("/api/pull"), + resp = self._client.get( + "/api/pull", params={"job_submission_id": str(job_submission_id), "timestamp": timestamp}, timeout=REQUEST_TIMEOUT, ) @@ -342,34 +340,31 @@ def pull(self, job_submission_id: uuid.UUID, timestamp: int) -> PullResponse: return self._response(PullResponse, resp) def stop(self, job_submission_id: uuid.UUID): - resp = self._session.post( - self._url("/api/stop"), + resp = self._client.post( + "/api/stop", params={"job_submission_id": str(job_submission_id)}, timeout=REQUEST_TIMEOUT, ) self._raise_for_job_submission_status(resp) - def _url(self, path: str) -> str: - return f"{self._base_url}/{path.lstrip('/')}" - - def _response(self, model_cls: type[_M], response: requests.Response) -> _M: + def _response(self, model_cls: type[_M], response: httpx2.Response) -> _M: try: return validate_json_extra_ignore(model_cls, response.content) except pydantic.ValidationError as e: raise RunnerResponseBodyError(response, e) from e - def _raise_for_status(self, response: requests.Response) -> None: + def _raise_for_status(self, response: httpx2.Response) -> None: if response.status_code >= HTTPStatus.BAD_REQUEST: raise RunnerResponseStatusError(response) - def _raise_for_job_submission_status(self, response: requests.Response) -> None: + def _raise_for_job_submission_status(self, response: httpx2.Response) -> None: """`_raise_for_status` for the endpoints that take `job_submission_id`.""" if response.status_code == HTTPStatus.CONFLICT: raise RunnerJobSubmissionMismatchError(response) self._raise_for_status(response) def _healthcheck(self) -> HealthcheckResponse: - resp = self._session.get(self._url("/api/healthcheck"), timeout=REQUEST_TIMEOUT) + resp = self._client.get("/api/healthcheck", timeout=REQUEST_TIMEOUT) self._raise_for_status(resp) return self._response(HealthcheckResponse, resp) @@ -456,7 +451,7 @@ def __init__( hostname: str = "localhost", uds: Optional[PathLike] = None, ): - self._session, self._base_url = _make_session_and_base_url(port, hostname, uds) + self._client = _make_client(port, hostname, uds) @classmethod def from_address(cls, address: LocalAddress) -> Self: @@ -505,7 +500,7 @@ def healthcheck(self, unmask_exceptions: Literal[True]) -> HealthcheckResponse: def healthcheck(self, unmask_exceptions: bool = False) -> Optional[HealthcheckResponse]: try: resp = self._request("GET", "/api/healthcheck", raise_for_status=True) - except requests.exceptions.RequestException: + except httpx2.HTTPError: if unmask_exceptions: raise return None @@ -741,28 +736,27 @@ def _request( body: Optional[CoreModel] = None, *, raise_for_status: bool = False, - ) -> requests.Response: - url = f"{self._base_url}/{path.lstrip('/')}" + ) -> httpx2.Response: if body is not None: json = body.model_dump() else: json = None - resp = self._session.request(method, url, json=json, timeout=REQUEST_TIMEOUT) + resp = self._client.request(method, path, json=json, timeout=REQUEST_TIMEOUT) if raise_for_status: self._raise_for_status(resp) return resp - def _response(self, model_cls: type[_M], response: requests.Response) -> _M: + def _response(self, model_cls: type[_M], response: httpx2.Response) -> _M: try: return validate_json_extra_ignore(model_cls, response.content) except pydantic.ValidationError as e: raise ShimResponseBodyError(response, e) from e - def _raise_for_status(self, response: requests.Response) -> None: + def _raise_for_status(self, response: httpx2.Response) -> None: if response.status_code >= HTTPStatus.BAD_REQUEST: raise ShimResponseStatusError(response) - def _negotiate(self, healthcheck_response: Optional[requests.Response] = None) -> None: + def _negotiate(self, healthcheck_response: Optional[httpx2.Response] = None) -> None: if healthcheck_response is None: healthcheck_response = self._request("GET", "/api/healthcheck", raise_for_status=True) version_string = self._response(HealthcheckResponse, healthcheck_response).version @@ -787,22 +781,20 @@ def _get_restart_safe_task_statuses(self) -> list[TaskStatus]: return statuses -def _make_session_and_base_url( - port: Optional[int], hostname: str, uds: Optional[PathLike] -) -> tuple[requests.Session, str]: +def _make_client(port: Optional[int], hostname: str, uds: Optional[PathLike]) -> HTTPClient: """ - Builds a session and base URL for HTTP over TCP (`port`) or over - a Unix domain socket (`uds`). Exactly one of the two must be specified. + Builds a client for HTTP over TCP (`port`) or over a Unix domain socket (`uds`). + Exactly one of the two must be specified. """ if (port is None) == (uds is None): raise ValueError("Either port or uds must be specified, not both") - session = requests.Session() if uds is not None: - base_url = f"http+unix://{urllib.parse.quote(str(uds), safe='')}" - session.mount("http+unix://", requests_unixsocket.UnixAdapter()) - else: - base_url = f"http://{hostname}:{port}" - return session, base_url + return HTTPClient( + base_url="http://localhost", + follow_redirects=True, + transport=httpx2.HTTPTransport(uds=str(uds)), + ) + return HTTPClient(base_url=f"http://{hostname}:{port}", follow_redirects=True) def healthcheck_response_to_instance_check( @@ -861,7 +853,7 @@ def _memory_to_bytes(memory: Optional[Memory]) -> int: return int(memory * 1024**3) -def _is_json_response(response: requests.Response) -> bool: +def _is_json_response(response: httpx2.Response) -> bool: content_type = response.headers.get("content-type") if not content_type: return False diff --git a/src/dstack/_internal/server/services/runner/ssh.py b/src/dstack/_internal/server/services/runner/ssh.py index bbc1c2389..2a096ed58 100644 --- a/src/dstack/_internal/server/services/runner/ssh.py +++ b/src/dstack/_internal/server/services/runner/ssh.py @@ -2,7 +2,7 @@ from collections.abc import Mapping from typing import Callable, Concatenate, Optional, ParamSpec, TypeVar -import requests +import httpx2 from dstack._internal.core.errors import SSHError from dstack._internal.core.models.runs import JobProvisioningData, JobRuntimeData @@ -75,7 +75,7 @@ def wrapper( raise PeerConnectionError(f"failed to open an SSH connection: {e}") from e try: return func(conn.forwarded_paths(), *args, **kwargs) - except requests.RequestException as e: + except httpx2.HTTPError as e: raise PeerConnectionError(f"the request did not get through: {e}") from e finally: conn.close() @@ -86,7 +86,7 @@ def wrapper( # b) stale control socket file left by killed master. # (Because we cannot rely solely on connection errors from `func` – it may swallow the errors.) # but we still want a fast retry in case master dies mid-request. - error: Optional[requests.ConnectionError] = None + error: Optional[httpx2.TransportError] = None for _ in range(2): conn = instance_connection_pool.get_or_open( ssh_private_key=ssh_private_key, @@ -97,12 +97,20 @@ def wrapper( raise PeerConnectionError("failed to open an SSH connection") try: return func(conn.forwarded_paths(), *args, **kwargs) - except requests.ConnectionError as e: + except _CONNECTION_ERRORS as e: instance_connection_pool.drop(conn.key) # dead ssh connection, re-open error = e - except requests.RequestException as e: + except httpx2.HTTPError as e: # Reached the peer, e.g. a read timeout — do not re-open the ssh connection raise PeerConnectionError(f"the request did not get through: {e}") from e raise PeerConnectionError(f"the request did not get through: {error}") from error return wrapper + + +_CONNECTION_ERRORS = (httpx2.NetworkError, httpx2.ConnectTimeout, httpx2.RemoteProtocolError) +""" +The errors that mean the connection to the peer could not be established, or was reset or +closed by the peer, which may be due to a dead SSH connection. Timeouts other than connect +timeouts mean the peer was reached. +""" diff --git a/src/dstack/_internal/server/testing/common.py b/src/dstack/_internal/server/testing/common.py index e1e7c2eff..a9404db01 100644 --- a/src/dstack/_internal/server/testing/common.py +++ b/src/dstack/_internal/server/testing/common.py @@ -9,7 +9,7 @@ from uuid import UUID import gpuhunt -import requests +import httpx2 from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import joinedload @@ -1437,10 +1437,11 @@ def get_runner_job_submission_mismatch_error( path: str = "/api/pull", ) -> RunnerJobSubmissionMismatchError: """The error `RunnerClient` raises when the runner has no job, e.g., after a restart.""" - response = requests.Response() - response.status_code = HTTPStatus.CONFLICT - response._content = b"no job submitted" - response.request = requests.Request(method="GET", url=f"http://localhost{path}").prepare() + response = httpx2.Response( + HTTPStatus.CONFLICT, + content=b"no job submitted", + request=httpx2.Request("GET", f"http://localhost{path}"), + ) return RunnerJobSubmissionMismatchError(response) diff --git a/src/dstack/_internal/server/utils/otel/utils.py b/src/dstack/_internal/server/utils/otel/utils.py index d3a79ec8d..d2831ea29 100644 --- a/src/dstack/_internal/server/utils/otel/utils.py +++ b/src/dstack/_internal/server/utils/otel/utils.py @@ -84,10 +84,9 @@ def _instrument(app: FastAPI, engine: AsyncEngine) -> None: SQLAlchemyInstrumentor().instrument(engine=engine.sync_engine) _register_db_span_renaming(engine.sync_engine) HTTPX2ClientInstrumentor().instrument() - # unixsocket calls to runners should not be instrumented: every runner - # tunnel has a unique socket path that becomes the net.peer.name metric - # attribute, so the SDK would accumulate state for an unbounded number of series. - RequestsInstrumentor().instrument(excluded_urls=r"http\+unix://") + # dstack's own HTTP calls use httpx2; requests remains in third-party libraries, + # e.g. python-dxf for Docker registries. + RequestsInstrumentor().instrument() if settings.OTEL_METRICS_ENABLED: SystemMetricsInstrumentor(config=otel_utils.PROCESS_METRICS_CONFIG).instrument() diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py index 47f6cc7a4..2ea8107ec 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py @@ -3,9 +3,9 @@ from typing import ClassVar, Optional from unittest.mock import Mock +import httpx2 import pytest import pytest_asyncio -import requests from gpuhunt import AcceleratorVendor from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession @@ -1228,7 +1228,7 @@ async def test_returns_none_on_request_error( instance: InstanceModel, shim_client_mock: Mock, ): - shim_client_mock.get_instance_info.side_effect = requests.RequestException("boom") + shim_client_mock.get_instance_info.side_effect = httpx2.ConnectError("boom") assert instances_check._get_gpu_driver(instance, shim_client_mock) is None diff --git a/src/tests/_internal/server/services/runner/test_client.py b/src/tests/_internal/server/services/runner/test_client.py index 9a0f4d81b..d5b5da02f 100644 --- a/src/tests/_internal/server/services/runner/test_client.py +++ b/src/tests/_internal/server/services/runner/test_client.py @@ -1,11 +1,11 @@ import uuid -from collections.abc import Callable, Generator +from collections.abc import Callable from datetime import datetime, timezone +from pathlib import Path from typing import Optional +import httpx2 import pytest -import requests -import requests_mock from gpuhunt import AcceleratorVendor from dstack._internal.core.consts import DSTACK_RUNNER_HTTP_PORT, DSTACK_SHIM_HTTP_PORT @@ -48,44 +48,41 @@ get_volume, get_volume_configuration, ) +from tests.http_mock import HTTPMock +RUNNER_URL = f"http://localhost:{DSTACK_RUNNER_HTTP_PORT}" +SHIM_URL = f"http://localhost:{DSTACK_SHIM_HTTP_PORT}" -class BaseShimClientTest: - @pytest.fixture - def adapter(self) -> Generator[requests_mock.Adapter, None, None]: - adapter = requests_mock.Adapter() - with requests_mock.Mocker(adapter=adapter): - yield adapter - return +class BaseShimClientTest: @pytest.fixture - def client(self, request: pytest.FixtureRequest, adapter: requests_mock.Adapter) -> ShimClient: + def client(self, request: pytest.FixtureRequest, http_mock: HTTPMock) -> ShimClient: shim_version_marker = request.node.get_closest_marker("shim_version") if shim_version_marker is not None: healthcheck_resp = {"service": "dstack-shim", "version": shim_version_marker.args[0]} - adapter.register_uri("GET", "/api/healthcheck", json=healthcheck_resp) + http_mock.get(f"{SHIM_URL}/api/healthcheck", json=healthcheck_resp) return ShimClient(port=DSTACK_SHIM_HTTP_PORT, hostname="localhost") def assert_request( self, - adapter: requests_mock.Adapter, + http_mock: HTTPMock, index: int, method: str, path: str, json: Optional[dict] = None, ): - history = adapter.request_history + history = http_mock.request_history assert index < len(history), "index out of history bounds" req = history[index] assert req.method == method - assert req.path == path + assert req.url.path == path if json is not None: assert req.json() == json class TestRunnerClientSubmitJob(BaseShimClientTest): - def test_adds_default_project_for_server_access(self, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/submit", json={}) + def test_adds_default_project_for_server_access(self, http_mock: HTTPMock): + http_mock.post(f"{RUNNER_URL}/api/submit", json={}) run_spec = get_run_spec( repo_id="repo", configuration=TaskConfiguration(commands=["true"], dstack=True) ) @@ -109,15 +106,15 @@ def test_adds_default_project_for_server_access(self, adapter: requests_mock.Ada repo_credentials=None, ) - assert adapter.last_request is not None - assert adapter.last_request.json()["job_spec"]["env"] == { + assert http_mock.last_request is not None + assert http_mock.last_request.json()["job_spec"]["env"] == { "DSTACK_PROJECT": "main", "DSTACK_TOKEN": "token", } assert job.job_spec.env == {"DSTACK_TOKEN": "token"} - def test_preserves_explicit_project_for_server_access(self, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/submit", json={}) + def test_preserves_explicit_project_for_server_access(self, http_mock: HTTPMock): + http_mock.post(f"{RUNNER_URL}/api/submit", json={}) run_spec = get_run_spec( repo_id="repo", configuration=TaskConfiguration(commands=["true"], dstack=True) ) @@ -141,14 +138,41 @@ def test_preserves_explicit_project_for_server_access(self, adapter: requests_mo repo_credentials=None, ) - assert adapter.last_request is not None - assert adapter.last_request.json()["job_spec"]["env"]["DSTACK_PROJECT"] == "other" + assert http_mock.last_request is not None + assert http_mock.last_request.json()["job_spec"]["env"]["DSTACK_PROJECT"] == "other" + + +class TestRunnerClientUploadCode(BaseShimClientTest): + def test_sends_code_as_body(self, http_mock: HTTPMock): + http_mock.post(f"{RUNNER_URL}/api/upload_code") + client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) + + client.upload_code(b"code") + + assert http_mock.last_request.content == b"code" + assert http_mock.last_request.timeout["read"] == 60 + + +class TestRunnerClientUnixSocket: + def test_requests_localhost(self, http_mock: HTTPMock, tmp_path: Path): + http_mock.get( + "http://localhost/api/healthcheck", + json={"service": "dstack-runner", "version": "0.20.0"}, + ) + client = RunnerClient.from_address(tmp_path / "runner.sock") + + assert client.healthcheck() == HealthcheckResponse( + service="dstack-runner", version="0.20.0" + ) class TestRunnerClientResponseErrors(BaseShimClientTest): - def test_status_error_reports_endpoint_status_and_body(self, adapter: requests_mock.Adapter): - adapter.register_uri( - "POST", "/api/run", status_code=502, reason="Bad Gateway", text="upstream is down" + def test_status_error_reports_endpoint_status_and_body(self, http_mock: HTTPMock): + http_mock.post( + f"{RUNNER_URL}/api/run", + status_code=502, + extensions={"reason_phrase": b"Bad Gateway"}, + text="upstream is down", ) client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) @@ -163,10 +187,10 @@ def test_status_error_reports_endpoint_status_and_body(self, adapter: requests_m assert str(exc) == "POST /api/run: 502: upstream is down" assert repr(exc) == "RunnerResponseStatusError(502)" # API errors must not be confused with connection errors - assert not isinstance(exc, requests.RequestException) + assert not isinstance(exc, httpx2.HTTPError) - def test_status_error_without_body(self, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/run", status_code=500, text="") + def test_status_error_without_body(self, http_mock: HTTPMock): + http_mock.post(f"{RUNNER_URL}/api/run", status_code=500, text="") client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) with pytest.raises(RunnerResponseStatusError) as excinfo: @@ -174,8 +198,8 @@ def test_status_error_without_body(self, adapter: requests_mock.Adapter): assert str(excinfo.value) == "POST /api/run: 500: " - def test_status_error_truncates_long_body(self, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/run", status_code=500, text="x" * 4096) + def test_status_error_truncates_long_body(self, http_mock: HTTPMock): + http_mock.post(f"{RUNNER_URL}/api/run", status_code=500, text="x" * 4096) client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) with pytest.raises(RunnerResponseStatusError) as excinfo: @@ -185,8 +209,8 @@ def test_status_error_truncates_long_body(self, adapter: requests_mock.Adapter): assert message.endswith("x" * 512 + "...") assert len(message) < 600 - def test_body_error_on_malformed_json(self, adapter: requests_mock.Adapter): - adapter.register_uri("GET", "/api/healthcheck", text="not json") + def test_body_error_on_malformed_json(self, http_mock: HTTPMock): + http_mock.get(f"{RUNNER_URL}/api/healthcheck", text="not json") client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) with pytest.raises(RunnerResponseBodyError) as excinfo: @@ -196,11 +220,11 @@ def test_body_error_on_malformed_json(self, adapter: requests_mock.Adapter): assert str(exc).startswith("GET /api/healthcheck: 1 validation error(s)") assert str(exc).endswith("body: not json") # Parsing the body with pydantic rather than `Response.json()` keeps this out of the - # `requests.RequestException` hierarchy, where the tunnel would read it as transport. - assert not isinstance(exc, requests.RequestException) + # `httpx2.HTTPError` hierarchy, where the tunnel would read it as transport. + assert not isinstance(exc, httpx2.HTTPError) - def test_body_error_on_schema_mismatch(self, adapter: requests_mock.Adapter): - adapter.register_uri("GET", "/api/healthcheck", json={"service": "dstack-runner"}) + def test_body_error_on_schema_mismatch(self, http_mock: HTTPMock): + http_mock.get(f"{RUNNER_URL}/api/healthcheck", json={"service": "dstack-runner"}) client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) with pytest.raises(RunnerResponseBodyError) as excinfo: @@ -210,16 +234,14 @@ def test_body_error_on_schema_mismatch(self, adapter: requests_mock.Adapter): assert "first at version: Field required" in str(exc) assert exc.error.error_count() == 1 - def test_healthcheck_returns_none_on_connection_error(self, adapter: requests_mock.Adapter): - adapter.register_uri( - "GET", "/api/healthcheck", exc=requests.exceptions.ConnectionError("refused") - ) + def test_healthcheck_returns_none_on_connection_error(self, http_mock: HTTPMock): + http_mock.get(f"{RUNNER_URL}/api/healthcheck", exc=httpx2.ConnectError("refused")) client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) assert client.healthcheck() is None - def test_healthcheck_raises_on_error_status(self, adapter: requests_mock.Adapter): - adapter.register_uri("GET", "/api/healthcheck", status_code=500) + def test_healthcheck_raises_on_error_status(self, http_mock: HTTPMock): + http_mock.get(f"{RUNNER_URL}/api/healthcheck", status_code=500) client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) with pytest.raises(RunnerResponseStatusError): @@ -237,20 +259,20 @@ class TestRunnerClientJobSubmissionScoped(BaseShimClientTest): ) def test_raises_mismatch_error_on_conflict( self, - adapter: requests_mock.Adapter, + http_mock: HTTPMock, method: str, path: str, call: Callable[[RunnerClient, uuid.UUID], object], ): - adapter.register_uri(method, path, status_code=409, text="no job submitted") + http_mock.register(method, RUNNER_URL + path, status_code=409, text="no job submitted") client = RunnerClient(port=DSTACK_RUNNER_HTTP_PORT) job_submission_id = uuid.uuid4() with pytest.raises(RunnerJobSubmissionMismatchError) as excinfo: call(client, job_submission_id) - assert adapter.last_request is not None - assert adapter.last_request.qs["job_submission_id"] == [str(job_submission_id)] + assert http_mock.last_request is not None + assert http_mock.last_request.qs["job_submission_id"] == [str(job_submission_id)] assert str(excinfo.value).endswith(": 409: no job submitted") @@ -278,7 +300,7 @@ class TestShimClientNegotiate(BaseShimClientTest): def test( self, client: ShimClient, - adapter: requests_mock.Adapter, + http_mock: HTTPMock, expected_shim_version: Optional[tuple[int, int, int]], expected_api_version: int, ): @@ -289,14 +311,17 @@ def test( assert client._shim_version_tuple == expected_shim_version assert client._api_version == expected_api_version - assert adapter.call_count == 1 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") + assert http_mock.call_count == 1 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") class TestShimClientResponseErrors(BaseShimClientTest): - def test_status_error(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri( - "GET", "/test/path", status_code=502, reason="Bad Gateway", text="Task not found" + def test_status_error(self, client: ShimClient, http_mock: HTTPMock): + http_mock.get( + f"{SHIM_URL}/test/path", + status_code=502, + extensions={"reason_phrase": b"Bad Gateway"}, + text="Task not found", ) response = client._request("GET", "/test/path") @@ -308,8 +333,8 @@ def test_status_error(self, client: ShimClient, adapter: requests_mock.Adapter): assert str(exc) == "GET /test/path: 502: Task not found" assert repr(exc) == "ShimResponseStatusError(502)" - def test_body_error(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri("GET", "/test/path", json={"service": "dstack-shim"}) + def test_body_error(self, client: ShimClient, http_mock: HTTPMock): + http_mock.get(f"{SHIM_URL}/test/path", json={"service": "dstack-shim"}) response = client._request("GET", "/test/path") with pytest.raises(ShimResponseBodyError) as excinfo: @@ -320,18 +345,18 @@ def test_body_error(self, client: ShimClient, adapter: requests_mock.Adapter): @pytest.mark.shim_version("0.18.30") class TestShimClientV1(BaseShimClientTest): - def test_healthcheck(self, client: ShimClient, adapter: requests_mock.Adapter): + def test_healthcheck(self, client: ShimClient, http_mock: HTTPMock): resp = client.healthcheck() assert resp == HealthcheckResponse(service="dstack-shim", version="0.18.30") - assert adapter.call_count == 1 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") + assert http_mock.call_count == 1 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") # healthcheck() method also performs negotiation to save API calls assert client._shim_version_tuple == (0, 18, 30) assert client._api_version == 1 - def test_submit(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/submit", json={"state": "pulling"}) + def test_submit(self, client: ShimClient, http_mock: HTTPMock): + http_mock.post(f"{SHIM_URL}/api/submit", json={"state": "pulling"}) volume = get_volume( name="vol", volume_id="vol-id", @@ -363,7 +388,7 @@ def test_submit(self, client: ShimClient, adapter: requests_mock.Adapter): ) assert submitted is True - assert adapter.call_count == 1 + assert http_mock.call_count == 1 expected_request = { "username": "", "password": "", @@ -389,10 +414,10 @@ def test_submit(self, client: ShimClient, adapter: requests_mock.Adapter): {"instance_path": "/mnt/nfs/home", "path": "/home", "optional": False} ], } - self.assert_request(adapter, 0, "POST", "/api/submit", expected_request) + self.assert_request(http_mock, 0, "POST", "/api/submit", expected_request) - def test_submit_conflict(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/submit", status_code=409) + def test_submit_conflict(self, client: ShimClient, http_mock: HTTPMock): + http_mock.post(f"{SHIM_URL}/api/submit", status_code=409) submitted = client.submit( username="", @@ -412,29 +437,28 @@ def test_submit_conflict(self, client: ShimClient, adapter: requests_mock.Adapte ) assert submitted is False - assert adapter.call_count == 1 - self.assert_request(adapter, 0, "POST", "/api/submit") + assert http_mock.call_count == 1 + self.assert_request(http_mock, 0, "POST", "/api/submit") - def test_stop(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/stop", json={"state": "pending"}) + def test_stop(self, client: ShimClient, http_mock: HTTPMock): + http_mock.post(f"{SHIM_URL}/api/stop", json={"state": "pending"}) client.stop() - assert adapter.call_count == 1 - self.assert_request(adapter, 0, "POST", "/api/stop", {"force": False}) + assert http_mock.call_count == 1 + self.assert_request(http_mock, 0, "POST", "/api/stop", {"force": False}) - def test_stop_force(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/stop", json={"state": "pending"}) + def test_stop_force(self, client: ShimClient, http_mock: HTTPMock): + http_mock.post(f"{SHIM_URL}/api/stop", json={"state": "pending"}) client.stop(force=True) - assert adapter.call_count == 1 - self.assert_request(adapter, 0, "POST", "/api/stop", {"force": True}) + assert http_mock.call_count == 1 + self.assert_request(http_mock, 0, "POST", "/api/stop", {"force": True}) - def test_pull(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri( - "GET", - "/api/pull", + def test_pull(self, client: ShimClient, http_mock: HTTPMock): + http_mock.get( + f"{SHIM_URL}/api/pull", json={ "state": "pending", "result": {"reason": "CONTAINER_EXITED_WITH_ERROR", "reason_message": "killed"}, @@ -447,28 +471,25 @@ def test_pull(self, client: ShimClient, adapter: requests_mock.Adapter): state="pending", result=JobResult(reason="CONTAINER_EXITED_WITH_ERROR", reason_message="killed"), ) - assert adapter.call_count == 1 - self.assert_request(adapter, 0, "GET", "/api/pull") + assert http_mock.call_count == 1 + self.assert_request(http_mock, 0, "GET", "/api/pull") @pytest.mark.shim_version("0.18.40") class TestShimClientV2(BaseShimClientTest): - def test_healthcheck(self, client: ShimClient, adapter: requests_mock.Adapter): + def test_healthcheck(self, client: ShimClient, http_mock: HTTPMock): resp = client.healthcheck() assert resp == HealthcheckResponse(service="dstack-shim", version="0.18.40") - assert adapter.call_count == 1 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") + assert http_mock.call_count == 1 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") # healthcheck() method also performs negotiation to save API calls assert client._shim_version_tuple == (0, 18, 40) assert client._api_version == 2 - def test_is_safe_to_restart_false_old_shim( - self, client: ShimClient, adapter: requests_mock.Adapter - ): - adapter.register_uri( - "GET", - "/api/tasks", + def test_is_safe_to_restart_false_old_shim(self, client: ShimClient, http_mock: HTTPMock): + http_mock.get( + f"{SHIM_URL}/api/tasks", json={ # pre-0.19.26 shim returns ids instead of tasks "tasks": None, @@ -479,9 +500,9 @@ def test_is_safe_to_restart_false_old_shim( res = client.is_safe_to_restart() assert res is False - assert adapter.call_count == 2 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") - self.assert_request(adapter, 1, "GET", "/api/tasks") + assert http_mock.call_count == 2 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") + self.assert_request(http_mock, 1, "GET", "/api/tasks") @pytest.mark.parametrize( "task_status", @@ -494,11 +515,10 @@ def test_is_safe_to_restart_false_old_shim( ], ) def test_is_safe_to_restart_false_status_not_safe( - self, client: ShimClient, adapter: requests_mock.Adapter, task_status: TaskStatus + self, client: ShimClient, http_mock: HTTPMock, task_status: TaskStatus ): - adapter.register_uri( - "GET", - "/api/tasks", + http_mock.get( + f"{SHIM_URL}/api/tasks", json={ "tasks": [ { @@ -517,14 +537,13 @@ def test_is_safe_to_restart_false_status_not_safe( res = client.is_safe_to_restart() assert res is False - assert adapter.call_count == 2 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") - self.assert_request(adapter, 1, "GET", "/api/tasks") - - def test_is_safe_to_restart_true(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri( - "GET", - "/api/tasks", + assert http_mock.call_count == 2 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") + self.assert_request(http_mock, 1, "GET", "/api/tasks") + + def test_is_safe_to_restart_true(self, client: ShimClient, http_mock: HTTPMock): + http_mock.get( + f"{SHIM_URL}/api/tasks", json={ "tasks": [ { @@ -544,16 +563,15 @@ def test_is_safe_to_restart_true(self, client: ShimClient, adapter: requests_moc res = client.is_safe_to_restart() assert res is True - assert adapter.call_count == 2 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") - self.assert_request(adapter, 1, "GET", "/api/tasks") + assert http_mock.call_count == 2 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") + self.assert_request(http_mock, 1, "GET", "/api/tasks") - def test_get_task(self, client: ShimClient, adapter: requests_mock.Adapter): + def test_get_task(self, client: ShimClient, http_mock: HTTPMock): task_id = "d35b6e24-b556-4d6e-81e3-5982d2c34449" url = f"/api/tasks/{task_id}" - adapter.register_uri( - "GET", - url, + http_mock.get( + SHIM_URL + url, json={ "id": task_id, "status": "terminated", @@ -579,12 +597,12 @@ def test_get_task(self, client: ShimClient, adapter: requests_mock.Adapter): PortMapping(host=34771, container=10999), ], ) - assert adapter.call_count == 2 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") - self.assert_request(adapter, 1, "GET", url) + assert http_mock.call_count == 2 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") + self.assert_request(http_mock, 1, "GET", url) - def test_submit_task(self, client: ShimClient, adapter: requests_mock.Adapter): - adapter.register_uri("POST", "/api/tasks", status_code=200) + def test_submit_task(self, client: ShimClient, http_mock: HTTPMock): + http_mock.post(f"{SHIM_URL}/api/tasks", status_code=200) volume = get_volume( name="vol", volume_id="vol-id", @@ -621,8 +639,8 @@ def test_submit_task(self, client: ShimClient, adapter: requests_mock.Adapter): instance_id="i-1", ) - assert adapter.call_count == 2 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") + assert http_mock.call_count == 2 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") expected_request = { "id": "c514f4ee-dfe7-472c-99a3-047178aafb5b", "name": "test-0-0", @@ -654,52 +672,50 @@ def test_submit_task(self, client: ShimClient, adapter: requests_mock.Adapter): "host_ssh_keys": ["host_key"], "container_ssh_keys": ["project_key", "user_key"], } - self.assert_request(adapter, 1, "POST", "/api/tasks", expected_request) + self.assert_request(http_mock, 1, "POST", "/api/tasks", expected_request) - def test_terminate_task(self, client: ShimClient, adapter: requests_mock.Adapter): + def test_terminate_task(self, client: ShimClient, http_mock: HTTPMock): task_id = "c514f4ee-dfe7-472c-99a3-047178aafb5b" url = f"/api/tasks/{task_id}/terminate" - adapter.register_uri("POST", url, status_code=200) + http_mock.post(SHIM_URL + url, status_code=200) client.terminate_task(uuid.UUID(task_id), "TEST_REASON", "test message", timeout=5) - assert adapter.call_count == 2 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") + assert http_mock.call_count == 2 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") expected_request = { "termination_reason": "TEST_REASON", "termination_message": "test message", "timeout": 5, } - self.assert_request(adapter, 1, "POST", url, expected_request) + self.assert_request(http_mock, 1, "POST", url, expected_request) - def test_terminate_task_default_params( - self, client: ShimClient, adapter: requests_mock.Adapter - ): + def test_terminate_task_default_params(self, client: ShimClient, http_mock: HTTPMock): task_id = uuid.UUID("c514f4ee-dfe7-472c-99a3-047178aafb5b") url = f"/api/tasks/{task_id}/terminate" - adapter.register_uri("POST", url, status_code=200) + http_mock.post(SHIM_URL + url, status_code=200) client.terminate_task(task_id) - assert adapter.call_count == 2 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") + assert http_mock.call_count == 2 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") expected_request = { "termination_reason": "", "termination_message": "", "timeout": 10, } - self.assert_request(adapter, 1, "POST", url, expected_request) + self.assert_request(http_mock, 1, "POST", url, expected_request) - def test_remove_task(self, client: ShimClient, adapter: requests_mock.Adapter): + def test_remove_task(self, client: ShimClient, http_mock: HTTPMock): task_id = "c514f4ee-dfe7-472c-99a3-047178aafb5b" url = f"/api/tasks/{task_id}/remove" - adapter.register_uri("POST", url, status_code=200) + http_mock.post(SHIM_URL + url, status_code=200) client.remove_task(uuid.UUID(task_id)) - assert adapter.call_count == 2 - self.assert_request(adapter, 0, "GET", "/api/healthcheck") - self.assert_request(adapter, 1, "POST", url) + assert http_mock.call_count == 2 + self.assert_request(http_mock, 0, "GET", "/api/healthcheck") + self.assert_request(http_mock, 1, "POST", url) class TestParseVersion: @@ -770,28 +786,25 @@ def test_gpu_driver(self): class TestShimClientGetInstanceInfo(BaseShimClientTest): @pytest.mark.shim_version("0.21.0") - def test_returns_instance_info(self, adapter: requests_mock.Adapter, client: ShimClient): - adapter.register_uri( - "GET", - "/api/instance/info", + def test_returns_instance_info(self, http_mock: HTTPMock, client: ShimClient): + http_mock.get( + f"{SHIM_URL}/api/instance/info", json={"gpu_vendor": "nvidia", "gpu_driver_version": "570.86.15"}, ) resp = client.get_instance_info() assert resp is not None assert resp.gpu_vendor == "nvidia" assert resp.gpu_driver_version == "570.86.15" - self.assert_request(adapter, 1, "GET", "/api/instance/info") + self.assert_request(http_mock, 1, "GET", "/api/instance/info") @pytest.mark.shim_version("0.20.29") - def test_returns_none_if_not_supported( - self, adapter: requests_mock.Adapter, client: ShimClient - ): + def test_returns_none_if_not_supported(self, http_mock: HTTPMock, client: ShimClient): assert client.get_instance_info() is None - assert len(adapter.request_history) == 1 # healthcheck only + assert len(http_mock.request_history) == 1 # healthcheck only @pytest.mark.shim_version("latest") - def test_returns_none_if_not_found(self, adapter: requests_mock.Adapter, client: ShimClient): - adapter.register_uri("GET", "/api/instance/info", status_code=404, text="Not Found") + def test_returns_none_if_not_found(self, http_mock: HTTPMock, client: ShimClient): + http_mock.get(f"{SHIM_URL}/api/instance/info", status_code=404, text="Not Found") assert client.get_instance_info() is None # An unknown shim version is assumed to support the endpoint, so it is requested - self.assert_request(adapter, 1, "GET", "/api/instance/info") + self.assert_request(http_mock, 1, "GET", "/api/instance/info") diff --git a/src/tests/_internal/server/services/runner/test_ssh.py b/src/tests/_internal/server/services/runner/test_ssh.py index 5586e7243..f2d9435ab 100644 --- a/src/tests/_internal/server/services/runner/test_ssh.py +++ b/src/tests/_internal/server/services/runner/test_ssh.py @@ -2,9 +2,9 @@ from pathlib import Path from unittest.mock import Mock, patch +import httpx2 import pydantic import pytest -import requests from dstack._internal.core.consts import DSTACK_SHIM_HTTP_PORT from dstack._internal.core.errors import SSHError @@ -22,14 +22,12 @@ FORWARDED_PATHS = {DSTACK_SHIM_HTTP_PORT: Path("/tmp/shim.sock")} -def _shim_response(status_code: int, content: bytes) -> requests.Response: - response = requests.Response() - response.status_code = status_code - response._content = content - response.request = requests.Request( - method="GET", url="http://localhost/api/tasks/id" - ).prepare() - return response +def _shim_response(status_code: int, content: bytes) -> httpx2.Response: + return httpx2.Response( + status_code, + content=content, + request=httpx2.Request("GET", "http://localhost/api/tasks/id"), + ) def _make_error(error_cls: type[ShimResponseError]) -> ShimResponseError: @@ -87,9 +85,9 @@ def test_ssh_error_on_open_raises(self, conn): @pytest.mark.parametrize( "exc", [ - requests.ConnectionError("refused"), - requests.ReadTimeout("too slow"), - requests.exceptions.ChunkedEncodingError("truncated"), + httpx2.ConnectError("refused"), + httpx2.ReadTimeout("too slow"), + httpx2.RemoteProtocolError("truncated"), ], ) def test_connection_errors_raise(self, conn, exc): @@ -128,9 +126,16 @@ def test_returns_result(self, pool): assert self.call(lambda addresses: "result", dockerized=True) == "result" assert pool.drop.call_count == 0 - def test_connection_error_drops_and_retries_once(self, pool): - error = requests.ConnectionError("refused") - + @pytest.mark.parametrize( + "error", + [ + httpx2.ConnectError("refused"), + httpx2.ConnectTimeout("connect timed out"), + httpx2.ReadError("connection reset"), + httpx2.RemoteProtocolError("server disconnected"), + ], + ) + def test_connection_error_drops_and_retries_once(self, pool, error): def func(addresses: Mapping[int, LocalAddress]): raise error @@ -142,7 +147,7 @@ def func(addresses: Mapping[int, LocalAddress]): def test_other_connection_errors_do_not_retry(self, pool): def func(addresses: Mapping[int, LocalAddress]): - raise requests.ReadTimeout("too slow") + raise httpx2.ReadTimeout("too slow") with pytest.raises(PeerConnectionError, match="did not get through"): self.call(func, dockerized=True) From 81f830d4ede848e3307d99068ae405e5864c4d22 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:19:12 +0500 Subject: [PATCH 04/37] Move backend API clients to httpx2 --- .../_internal/core/backends/base/compute.py | 27 ++-- .../core/backends/cloudrift/api_client.py | 25 ++-- .../core/backends/cloudrift/compute.py | 3 + .../_internal/core/backends/crusoe/compute.py | 3 + .../core/backends/crusoe/resources.py | 13 +- .../core/backends/daytona/api_client.py | 17 ++- .../core/backends/daytona/compute.py | 3 + .../backends/digitalocean_base/api_client.py | 15 ++- .../backends/digitalocean_base/compute.py | 3 + .../core/backends/hotaisle/api_client.py | 32 +++-- .../core/backends/hotaisle/compute.py | 3 + .../core/backends/jarvislabs/api_client.py | 15 ++- .../core/backends/jarvislabs/compute.py | 3 + .../core/backends/lambdalabs/api_client.py | 22 ++-- .../core/backends/lambdalabs/compute.py | 3 + .../core/backends/lium/api_client.py | 15 ++- .../_internal/core/backends/lium/compute.py | 3 + .../core/backends/massedcompute/api_client.py | 17 ++- .../core/backends/massedcompute/compute.py | 3 + .../core/backends/runpod/api_client.py | 22 ++-- .../_internal/core/backends/runpod/compute.py | 3 + .../core/backends/seeweb/api_client.py | 39 +++--- .../_internal/core/backends/seeweb/compute.py | 3 + .../core/backends/vultr/api_client.py | 28 ++-- .../_internal/core/backends/vultr/compute.py | 9 +- .../backends/cloudrift/test_api_client.py | 67 +++++----- .../core/backends/daytona/test_api_client.py | 124 +++++++++--------- .../core/backends/daytona/test_compute.py | 12 +- .../backends/daytona/test_configurator.py | 8 +- .../core/backends/hotaisle/test_api_client.py | 44 +++---- .../backends/jarvislabs/test_api_client.py | 98 +++++++------- .../core/backends/lium/test_api_client.py | 112 ++++++++-------- .../core/backends/lium/test_configurator.py | 8 +- .../backends/massedcompute/test_api_client.py | 14 +- .../backends/massedcompute/test_compute.py | 14 +- .../core/backends/runpod/test_api_client.py | 60 ++++----- .../core/backends/seeweb/test_api_client.py | 64 ++++----- 37 files changed, 517 insertions(+), 437 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/compute.py b/src/dstack/_internal/core/backends/base/compute.py index 0b701639a..aeef66bcd 100644 --- a/src/dstack/_internal/core/backends/base/compute.py +++ b/src/dstack/_internal/core/backends/base/compute.py @@ -14,7 +14,6 @@ from typing import Callable, ClassVar, Dict, List, Optional, Union import git -import requests import yaml from cachetools import Cache, TTLCache, cachedmethod from gpuhunt import CPUArchitecture @@ -54,6 +53,7 @@ VolumeProvisioningData, ) from dstack._internal.core.services import is_valid_dstack_resource_name +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger from dstack._internal.utils.path import PathLike @@ -1381,17 +1381,17 @@ def get_latest_runner_build() -> Optional[str]: else: return None - resp = requests.get( - f"https://api.github.com/repos/{owner_repo}/actions/workflows/{workflow_id}/runs", - headers={ - "Accept": "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28", - }, - params={ - "status": "success", - }, - timeout=10, - ) + with HTTPClient(timeout=10, follow_redirects=True) as client: + resp = client.get( + f"https://api.github.com/repos/{owner_repo}/actions/workflows/{workflow_id}/runs", + headers={ + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + params={ + "status": "success", + }, + ) resp.raise_for_status() head = repo.head.commit @@ -1469,7 +1469,8 @@ def requires_nvidia_proprietary_kernel_modules(gpu_name: str) -> bool: def _fetch_version(url: str) -> Optional[str]: - r = requests.get(url, timeout=5) + with HTTPClient(timeout=5, follow_redirects=True) as client: + r = client.get(url) r.raise_for_status() version = r.text.strip() if not version: diff --git a/src/dstack/_internal/core/backends/cloudrift/api_client.py b/src/dstack/_internal/core/backends/cloudrift/api_client.py index 55601135d..8967d252e 100644 --- a/src/dstack/_internal/core/backends/cloudrift/api_client.py +++ b/src/dstack/_internal/core/backends/cloudrift/api_client.py @@ -1,12 +1,13 @@ +import json import os import re from typing import Any, Dict, List, Mapping, Optional, Union -import requests +import httpx2 from packaging import version -from requests import Response from dstack._internal.core.errors import BackendError, BackendInvalidCredentialsError +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) @@ -20,6 +21,10 @@ class RiftClient: def __init__(self, api_key: Optional[str] = None): self.public_api_root = os.path.join(CLOUDRIFT_SERVER_ADDRESS, "api/v1") self.api_key = api_key + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def validate_api_key(self) -> bool: """ @@ -185,7 +190,7 @@ def _make_request( data: Optional[Mapping[str, Any]] = None, method: str = "POST", **kwargs, - ) -> Union[Mapping[str, Any], str, Response]: + ) -> Union[Mapping[str, Any], str, httpx2.Response]: headers = {} if self.api_key is not None: headers["X-API-Key"] = self.api_key @@ -194,7 +199,7 @@ def _make_request( full_url = f"{self.public_api_root}/{endpoint}" try: - response = requests.request( + response = self._client.request( method, full_url, headers=headers, @@ -203,7 +208,7 @@ def _make_request( **kwargs, ) - if not response.ok: + if response.is_error: response.raise_for_status() try: response_json = response.json() @@ -216,12 +221,12 @@ def _make_request( response_json["version"], ) return response_json["data"] - except requests.exceptions.JSONDecodeError: + except json.JSONDecodeError: return response - except requests.HTTPError as e: - if e.response is not None and e.response.status_code in ( - requests.codes.forbidden, - requests.codes.unauthorized, + except httpx2.HTTPStatusError as e: + if e.response.status_code in ( + httpx2.codes.FORBIDDEN, + httpx2.codes.UNAUTHORIZED, ): raise BackendInvalidCredentialsError(e.response.text) raise diff --git a/src/dstack/_internal/core/backends/cloudrift/compute.py b/src/dstack/_internal/core/backends/cloudrift/compute.py index 8a505ee0d..588c7371f 100644 --- a/src/dstack/_internal/core/backends/cloudrift/compute.py +++ b/src/dstack/_internal/core/backends/cloudrift/compute.py @@ -40,6 +40,9 @@ def __init__(self, config: CloudRiftConfig): self.config = config self.client = RiftClient(self.config.creds.api_key) + def close(self) -> None: + self.client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/crusoe/compute.py b/src/dstack/_internal/core/backends/crusoe/compute.py index f73dfaed6..028f123d4 100644 --- a/src/dstack/_internal/core/backends/crusoe/compute.py +++ b/src/dstack/_internal/core/backends/crusoe/compute.py @@ -138,6 +138,9 @@ def __init__(self, config: CrusoeConfig): ) ) + def close(self) -> None: + self._client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/crusoe/resources.py b/src/dstack/_internal/core/backends/crusoe/resources.py index 1f84ff401..b726960f8 100644 --- a/src/dstack/_internal/core/backends/crusoe/resources.py +++ b/src/dstack/_internal/core/backends/crusoe/resources.py @@ -5,10 +5,11 @@ import time from typing import Any, Dict, List, Optional -import requests +import httpx2 from dstack._internal.core.backends.crusoe.models import CrusoeAccessKeyCreds from dstack._internal.core.errors import BackendError, NoCapacityError, ProvisioningError +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) @@ -24,6 +25,10 @@ def __init__(self, creds: CrusoeAccessKeyCreds, project_id: str): self.access_key = creds.access_key self.secret_key = creds.secret_key self.project_id = project_id + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def _request( self, @@ -31,7 +36,7 @@ def _request( path: str, params: Optional[dict] = None, body: Optional[dict] = None, - ) -> requests.Response: + ) -> httpx2.Response: dt = str(datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0)) dt = dt.replace(" ", "T") @@ -55,7 +60,7 @@ def _request( headers["Content-Type"] = "application/json" url = f"{API_URL}{API_VERSION}{path}" - resp = requests.request( + resp = self._client.request( method, url, headers=headers, params=params, json=body, timeout=REQUEST_TIMEOUT ) if resp.status_code >= 400: @@ -187,7 +192,7 @@ def _wait_for_operation(self, operation_id, get_fn, timeout, interval) -> dict: time.sleep(interval) -def _raise_api_error(resp: requests.Response) -> None: +def _raise_api_error(resp: httpx2.Response) -> None: try: data = resp.json() message = data.get("message", data.get("error", str(data))) diff --git a/src/dstack/_internal/core/backends/daytona/api_client.py b/src/dstack/_internal/core/backends/daytona/api_client.py index c1a998105..674c66533 100644 --- a/src/dstack/_internal/core/backends/daytona/api_client.py +++ b/src/dstack/_internal/core/backends/daytona/api_client.py @@ -2,10 +2,11 @@ from typing import Any, Dict, List, Optional from urllib.parse import quote, urlsplit -import requests +import httpx2 from gpuhunt.providers.daytona import API_URL from dstack._internal.core.errors import BackendError, BackendInvalidCredentialsError +from dstack._internal.utils.http import HTTPClient REQUEST_TIMEOUT_SECONDS = 30 @@ -23,6 +24,10 @@ class DaytonaNotFoundError(DaytonaAPIError): class DaytonaAPIClient: def __init__(self, api_key: str): self.api_key = api_key + self._client = HTTPClient() + + def close(self) -> None: + self._client.close() def get_current_api_key(self) -> Dict[str, Any]: return _object(self._make_request("GET", "/api-keys/current")) @@ -186,18 +191,18 @@ def _request( params: Optional[Dict[str, Any]] = None, ) -> Any: try: - response = requests.request( + response = self._client.request( method=method, url=url, headers={"Authorization": f"Bearer {self.api_key}"}, json=json, params=params, timeout=REQUEST_TIMEOUT_SECONDS, - allow_redirects=False, + follow_redirects=False, ) - except requests.Timeout as e: + except httpx2.TimeoutException as e: raise DaytonaAPIError("Daytona API request timed out") from e - except requests.RequestException as e: + except httpx2.HTTPError as e: raise DaytonaAPIError("Daytona API request failed") from e if response.status_code == 401: raise BackendInvalidCredentialsError(fields=[["creds", "api_key"]]) @@ -250,7 +255,7 @@ def _validate_toolbox_url(url: str) -> None: raise DaytonaAPIError("Daytona returned an invalid toolbox proxy URL") -def _response_message(response: requests.Response) -> str: +def _response_message(response: httpx2.Response) -> str: message = f"Daytona API returned HTTP {response.status_code}" try: data = response.json() diff --git a/src/dstack/_internal/core/backends/daytona/compute.py b/src/dstack/_internal/core/backends/daytona/compute.py index 0b504ab89..ebb94edbb 100644 --- a/src/dstack/_internal/core/backends/daytona/compute.py +++ b/src/dstack/_internal/core/backends/daytona/compute.py @@ -60,6 +60,9 @@ def __init__(self, config: DaytonaConfig): self._catalog.add_provider(DaytonaProvider(api_key=config.creds.api_key)) self._organization_id: Optional[str] = None + def close(self) -> None: + self.api_client.close() + def get_offers_by_requirements( self, requirements: Requirements, full_offers: bool, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/digitalocean_base/api_client.py b/src/dstack/_internal/core/backends/digitalocean_base/api_client.py index fa901fc0d..03871e752 100644 --- a/src/dstack/_internal/core/backends/digitalocean_base/api_client.py +++ b/src/dstack/_internal/core/backends/digitalocean_base/api_client.py @@ -1,9 +1,10 @@ from typing import Any, Dict, List, Optional -import requests +import httpx2 from dstack._internal.core.backends.base.configurator import raise_invalid_credentials_error from dstack._internal.core.errors import NoCapacityError +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) @@ -13,14 +14,18 @@ class DigitalOceanAPIClient: def __init__(self, api_key: str, api_url: str): self.api_key = api_key self.base_url = api_url + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def validate_api_key(self) -> bool: try: response = self._make_request("GET", "/v2/account") response.raise_for_status() return True - except requests.HTTPError as e: - if e.response is not None and e.response.status_code == 401: + except httpx2.HTTPStatusError as e: + if e.response.status_code == 401: raise_invalid_credentials_error( fields=[["creds", "api_key"]], details="Invaild API key" ) @@ -87,13 +92,13 @@ def delete_droplet(self, droplet_id: str) -> None: def _make_request( self, method: str, endpoint: str, json: Optional[Dict[str, Any]] = None, timeout: int = 30 - ) -> requests.Response: + ) -> httpx2.Response: url = f"{self.base_url}{endpoint}" headers = { "Authorization": f"Bearer {self.api_key}", } - response = requests.request( + response = self._client.request( method=method, url=url, headers=headers, diff --git a/src/dstack/_internal/core/backends/digitalocean_base/compute.py b/src/dstack/_internal/core/backends/digitalocean_base/compute.py index 4c43664bb..37f574a08 100644 --- a/src/dstack/_internal/core/backends/digitalocean_base/compute.py +++ b/src/dstack/_internal/core/backends/digitalocean_base/compute.py @@ -63,6 +63,9 @@ def __init__(self, config: BaseDigitalOceanConfig, api_url: str, type: BackendTy DigitalOceanProvider(api_key=config.creds.api_key, api_url=api_url) ) + def close(self) -> None: + self.api_client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/hotaisle/api_client.py b/src/dstack/_internal/core/backends/hotaisle/api_client.py index 003953d80..aa3192902 100644 --- a/src/dstack/_internal/core/backends/hotaisle/api_client.py +++ b/src/dstack/_internal/core/backends/hotaisle/api_client.py @@ -1,9 +1,10 @@ from typing import Any, Dict, Optional -import requests +import httpx2 from dstack._internal.core.backends.base.configurator import raise_invalid_credentials_error from dstack._internal.core.errors import BackendError, NoCapacityError +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger API_URL = "https://admin.hotaisle.app/api" @@ -15,23 +16,26 @@ class HotAisleAPIClient: def __init__(self, api_key: str, team_handle: str): self.api_key = api_key self.team_handle = team_handle + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def validate_api_key(self) -> bool: url = f"{API_URL}/user/" try: response = self._make_request("GET", url) response.raise_for_status() - except requests.HTTPError as e: - if e.response is not None: - if e.response.status_code == 401: - raise_invalid_credentials_error( - fields=[["creds", "api_key"]], details="Invalid API key" - ) - if e.response.status_code == 403: - raise_invalid_credentials_error( - fields=[["creds", "api_key"]], - details="Authenticated user does not have required permissions", - ) + except httpx2.HTTPStatusError as e: + if e.response.status_code == 401: + raise_invalid_credentials_error( + fields=[["creds", "api_key"]], details="Invalid API key" + ) + if e.response.status_code == 403: + raise_invalid_credentials_error( + fields=[["creds", "api_key"]], + details="Authenticated user does not have required permissions", + ) raise user_data = response.json() @@ -128,7 +132,7 @@ def _make_request( json: Optional[dict[str, Any]] = None, params: Optional[dict[str, str]] = None, timeout: int = 30, - ) -> requests.Response: + ) -> httpx2.Response: headers = { "accept": "application/json", "Authorization": f"Token {self.api_key}", @@ -136,7 +140,7 @@ def _make_request( if json is not None: headers["Content-Type"] = "application/json" - return requests.request( + return self._client.request( method=method, url=url, headers=headers, diff --git a/src/dstack/_internal/core/backends/hotaisle/compute.py b/src/dstack/_internal/core/backends/hotaisle/compute.py index 5e1d79839..75dffe28e 100644 --- a/src/dstack/_internal/core/backends/hotaisle/compute.py +++ b/src/dstack/_internal/core/backends/hotaisle/compute.py @@ -60,6 +60,9 @@ def __init__(self, config: HotAisleConfig): HotAisleProvider(api_key=config.creds.api_key, team_handle=config.team_handle) ) + def close(self) -> None: + self.api_client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/jarvislabs/api_client.py b/src/dstack/_internal/core/backends/jarvislabs/api_client.py index 0a9a3b68d..87deb5b20 100644 --- a/src/dstack/_internal/core/backends/jarvislabs/api_client.py +++ b/src/dstack/_internal/core/backends/jarvislabs/api_client.py @@ -1,7 +1,7 @@ import hashlib from typing import Any, Dict, List, Optional -import requests +import httpx2 from gpuhunt.providers.jarvislabs import API_URL, JARVISLABS_REGION_URLS from dstack._internal.core.errors import ( @@ -9,6 +9,7 @@ BackendInvalidCredentialsError, NoCapacityError, ) +from dstack._internal.utils.http import HTTPClient TIMEOUT = 120 @@ -20,6 +21,10 @@ class JarvisLabsNotFoundError(BackendError): class JarvisLabsAPIClient: def __init__(self, api_key: str): self.api_key = api_key + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def validate_api_key(self) -> bool: try: @@ -204,7 +209,7 @@ def _make_request( region: Optional[str] = None, ) -> Any: try: - response = requests.request( + response = self._client.request( method=method, url=self._url(path=path, region=region), headers={"Authorization": f"Bearer {self.api_key}"}, @@ -212,9 +217,9 @@ def _make_request( params=params, timeout=TIMEOUT, ) - except requests.RequestException as e: + except httpx2.HTTPError as e: raise BackendError(f"JarvisLabs request failed: {e}") from e - if response.ok: + if not response.is_error: if not response.content: return {} try: @@ -290,7 +295,7 @@ def _coerce_bool(value: Any) -> bool: return bool(value) -def _get_response_error(response: requests.Response) -> str: +def _get_response_error(response: httpx2.Response) -> str: try: data = response.json() except ValueError: diff --git a/src/dstack/_internal/core/backends/jarvislabs/compute.py b/src/dstack/_internal/core/backends/jarvislabs/compute.py index 59f83c7a9..d5ce10418 100644 --- a/src/dstack/_internal/core/backends/jarvislabs/compute.py +++ b/src/dstack/_internal/core/backends/jarvislabs/compute.py @@ -81,6 +81,9 @@ def __init__(self, config: JarvisLabsConfig): self._catalog = gpuhunt.Catalog(balance_resources=False, auto_reload=False) self._catalog.add_provider(JarvisLabsProvider(api_key=self.config.creds.api_key)) + def close(self) -> None: + self.api_client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/lambdalabs/api_client.py b/src/dstack/_internal/core/backends/lambdalabs/api_client.py index 44874e9c7..cf56676ec 100644 --- a/src/dstack/_internal/core/backends/lambdalabs/api_client.py +++ b/src/dstack/_internal/core/backends/lambdalabs/api_client.py @@ -1,6 +1,8 @@ from typing import Any, Dict, List, Optional -import requests +import httpx2 + +from dstack._internal.utils.http import HTTPClient API_URL = "https://cloud.lambdalabs.com/api/v1" @@ -8,12 +10,16 @@ class LambdaAPIClient: def __init__(self, api_key: str): self.api_key = api_key + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def validate_api_key(self) -> bool: try: self.list_instance_types() - except requests.HTTPError as e: - if e.response is not None and e.response.status_code in [401, 403]: + except httpx2.HTTPStatusError as e: + if e.response.status_code in [401, 403]: return False raise e return True @@ -46,20 +52,20 @@ def launch_instances( "name": name, } resp = self._make_request("POST", "/instance-operations/launch", data) - if not resp.ok: + if resp.is_error: resp.raise_for_status() return resp.json()["data"]["instance_ids"] def terminate_instances(self, instance_ids: List[str]) -> List[str]: data = {"instance_ids": instance_ids} resp = self._make_request("POST", "/instance-operations/terminate", data) - if not resp.ok: + if resp.is_error: resp.raise_for_status() return resp.json()["data"] def list_ssh_keys(self) -> List[Dict]: resp = self._make_request("GET", "/ssh-keys") - if not resp.ok: + if resp.is_error: resp.raise_for_status() return resp.json()["data"] @@ -69,12 +75,12 @@ def add_ssh_key(self, name: str, public_key: str) -> List[Dict]: "public_key": public_key, } resp = self._make_request("POST", "/ssh-keys", data) - if not resp.ok: + if resp.is_error: resp.raise_for_status() return resp.json()["data"] def _make_request(self, method: str, path: str, data: Any = None): - return requests.request( + return self._client.request( method=method, url=API_URL + path, json=data, diff --git a/src/dstack/_internal/core/backends/lambdalabs/compute.py b/src/dstack/_internal/core/backends/lambdalabs/compute.py index f749e284c..67369260c 100644 --- a/src/dstack/_internal/core/backends/lambdalabs/compute.py +++ b/src/dstack/_internal/core/backends/lambdalabs/compute.py @@ -42,6 +42,9 @@ def __init__(self, config: LambdaConfig): self.config = config self.api_client = LambdaAPIClient(config.creds.api_key) + def close(self) -> None: + self.api_client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/lium/api_client.py b/src/dstack/_internal/core/backends/lium/api_client.py index c7ab749a9..0a1286b05 100644 --- a/src/dstack/_internal/core/backends/lium/api_client.py +++ b/src/dstack/_internal/core/backends/lium/api_client.py @@ -2,9 +2,10 @@ from typing import Any, Optional from urllib.parse import quote -import requests +import httpx2 from dstack._internal.core.errors import ComputeError +from dstack._internal.utils.http import HTTPClient API_URL = "https://lium.io/api" REQUEST_TIMEOUT_SECONDS = 30 @@ -27,6 +28,10 @@ def __init__( class LiumAPIClient: def __init__(self, api_key: str): self.api_key = api_key + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def get_user(self) -> dict[str, Any]: return _object(self._make_request("GET", "/users/me")) @@ -118,18 +123,18 @@ def _make_request( params: Optional[dict[str, Any]] = None, ) -> Any: try: - response = requests.request( + response = self._client.request( method=method, url=API_URL + path, headers={"X-API-Key": self.api_key, **(headers or {})}, json=json, params=params, timeout=REQUEST_TIMEOUT_SECONDS, - allow_redirects=False, + follow_redirects=False, ) - except requests.Timeout: + except httpx2.TimeoutException: raise LiumAPIError("Lium API request timed out") from None - except requests.RequestException: + except httpx2.HTTPError: raise LiumAPIError("Lium API request failed") from None if not 200 <= response.status_code < 300: code = None diff --git a/src/dstack/_internal/core/backends/lium/compute.py b/src/dstack/_internal/core/backends/lium/compute.py index c75fb807e..5aa3df2cc 100644 --- a/src/dstack/_internal/core/backends/lium/compute.py +++ b/src/dstack/_internal/core/backends/lium/compute.py @@ -86,6 +86,9 @@ def __init__(self, config: LiumConfig): self._catalog = gpuhunt.Catalog(balance_resources=False, auto_reload=False) self._catalog.add_provider(LiumProvider()) + def close(self) -> None: + self.api_client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/massedcompute/api_client.py b/src/dstack/_internal/core/backends/massedcompute/api_client.py index b77ca5ca1..d36eb2439 100644 --- a/src/dstack/_internal/core/backends/massedcompute/api_client.py +++ b/src/dstack/_internal/core/backends/massedcompute/api_client.py @@ -2,12 +2,13 @@ from urllib.parse import quote from uuid import UUID -import requests +import httpx2 from pydantic import AwareDatetime, Field, ValidationError from typing_extensions import TypedDict from dstack._internal.core.errors import BackendAuthError, ComputeError from dstack._internal.core.models.common import CoreModel, validate_json_extra_ignore +from dstack._internal.utils.http import HTTPClient API_URL = "https://vm.massedcompute.com/api/v1" _T = TypeVar("_T", bound=CoreModel) @@ -47,6 +48,10 @@ class _TerminateRequest(TypedDict, closed=True): class MassedComputeAPIClient: def __init__(self, api_key: str): self.api_key = api_key + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def validate_api_key(self) -> bool: try: @@ -99,17 +104,17 @@ def _request( method: str, path: str, payload: Optional[Union[_LaunchRequest, _TerminateRequest]] = None, - ) -> requests.Response: + ) -> httpx2.Response: try: - response = requests.request( + response = self._client.request( method, API_URL + path, json=payload, timeout=30, - allow_redirects=False, # A redirect can replay a launch POST. + follow_redirects=False, # A redirect can replay a launch POST. headers={"Authorization": f"Bearer {self.api_key}"}, ) - except requests.RequestException as e: + except httpx2.HTTPError as e: raise ComputeError(f"MassedCompute {method} {path}: {type(e).__name__}") from None if response.status_code == 401: raise BackendAuthError("Invalid MassedCompute API key") @@ -118,7 +123,7 @@ def _request( return response -def _parse_response(model: type[_T], response: requests.Response) -> _T: +def _parse_response(model: type[_T], response: httpx2.Response) -> _T: try: return validate_json_extra_ignore(model, response.content) except ValidationError: diff --git a/src/dstack/_internal/core/backends/massedcompute/compute.py b/src/dstack/_internal/core/backends/massedcompute/compute.py index 29940cdc0..2f763338e 100644 --- a/src/dstack/_internal/core/backends/massedcompute/compute.py +++ b/src/dstack/_internal/core/backends/massedcompute/compute.py @@ -49,6 +49,9 @@ def __init__(self, config: MassedComputeConfig): self.catalog = gpuhunt.Catalog(balance_resources=False, auto_reload=False) self.catalog.add_provider(MassedComputeProvider(config.creds.api_key)) + def close(self) -> None: + self.api_client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> list[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/runpod/api_client.py b/src/dstack/_internal/core/backends/runpod/api_client.py index 3d3bfbad8..51d52b504 100644 --- a/src/dstack/_internal/core/backends/runpod/api_client.py +++ b/src/dstack/_internal/core/backends/runpod/api_client.py @@ -2,10 +2,11 @@ from http import HTTPStatus from typing import Any, List, Literal, NotRequired, Optional, TypedDict, cast -import requests +import httpx2 from gpuhunt.providers.runpod import RunpodProvider from dstack._internal.core.errors import BackendError, BackendInvalidCredentialsError +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) @@ -214,8 +215,13 @@ def __repr__(self) -> str: class RunpodApiClient: def __init__(self, api_key: str): - self._session = requests.Session() - self._session.headers.update({"Authorization": f"Bearer {api_key}"}) + self._client = HTTPClient( + headers={"Authorization": f"Bearer {api_key}"}, + follow_redirects=True, + ) + + def close(self) -> None: + self._client.close() def validate_api_key(self) -> bool: try: @@ -404,9 +410,9 @@ def _make_v2_request( *path_parts: str, json: Optional[Mapping[str, Any]] = None, params: Optional[Mapping[str, Any]] = None, - ) -> requests.Response: + ) -> httpx2.Response: url = "/".join((API_V2_URL, *path_parts)) - response = self._session.request( + response = self._client.request( method=method, url=url, timeout=REQUEST_TIMEOUT, @@ -428,16 +434,16 @@ def _make_v2_request( return response -def _parse_v2_error_response(response: requests.Response) -> V2ErrorResponse: +def _parse_v2_error_response(response: httpx2.Response) -> V2ErrorResponse: try: error = response.json() - except requests.JSONDecodeError: + except ValueError: error = None if isinstance(error, dict) and "title" in error and "detail" in error: return cast(V2ErrorResponse, error) # Not a v2 error response, e.g., an HTML page served by a proxy in front of the API return { - "title": response.reason or "Unknown error", + "title": response.reason_phrase or "Unknown error", "status": response.status_code, "detail": " ".join(response.text.split())[:MAX_ERROR_DETAIL_LEN], } diff --git a/src/dstack/_internal/core/backends/runpod/compute.py b/src/dstack/_internal/core/backends/runpod/compute.py index 04e267780..0c3d61902 100644 --- a/src/dstack/_internal/core/backends/runpod/compute.py +++ b/src/dstack/_internal/core/backends/runpod/compute.py @@ -83,6 +83,9 @@ def __init__(self, config: RunpodConfig): self.catalog = gpuhunt.Catalog(balance_resources=False, auto_reload=False) self.catalog.add_provider(RunpodProvider(api_key=config.creds.api_key)) + def close(self) -> None: + self.api_client.close() + def get_offers_by_requirements( self, requirements: Requirements, full_offers: bool, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: diff --git a/src/dstack/_internal/core/backends/seeweb/api_client.py b/src/dstack/_internal/core/backends/seeweb/api_client.py index d486db67a..699bc581a 100644 --- a/src/dstack/_internal/core/backends/seeweb/api_client.py +++ b/src/dstack/_internal/core/backends/seeweb/api_client.py @@ -2,13 +2,14 @@ from dataclasses import dataclass from typing import Any, Dict, Optional -import requests +import httpx2 from dstack._internal.core.errors import ( BackendError, BackendInvalidCredentialsError, NoCapacityError, ) +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) @@ -26,27 +27,31 @@ class SeewebPlanAvailability: class SeewebApiClient: """Minimal client for the Seeweb ECS REST API (https://api.seeweb.it/ecs/v2). - Uses ``requests`` directly instead of the ``ecsapi`` SDK to avoid an extra dependency + Calls the REST API directly instead of using the ``ecsapi`` SDK to avoid an extra dependency for the handful of endpoints dstack needs. """ def __init__(self, api_token: str): self.api_token = api_token + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def _request( self, method: str, path: str, json: Optional[Dict[str, Any]] = None - ) -> requests.Response: + ) -> httpx2.Response: try: - response = requests.request( + response = self._client.request( method=method, url=API_URL + path, headers={"X-APITOKEN": self.api_token}, json=json, timeout=TIMEOUT, ) - except requests.RequestException as e: + except httpx2.HTTPError as e: raise BackendError(f"Seeweb API request failed: {e}") from e - if response.status_code in (requests.codes.unauthorized, requests.codes.forbidden): + if response.status_code in (httpx2.codes.unauthorized, httpx2.codes.forbidden): raise BackendInvalidCredentialsError(_response_message(response)) return response @@ -145,7 +150,7 @@ def create_server(self, body: Dict[str, Any]) -> tuple[Dict[str, Any], Optional[ def get_action(self, action_id: int) -> Optional[Dict[str, Any]]: response = self._request("GET", f"/actions/{action_id}") - if response.status_code == requests.codes.not_found: + if response.status_code == httpx2.codes.not_found: return None data = _response_data(response) action = data.get("action") @@ -153,7 +158,7 @@ def get_action(self, action_id: int) -> Optional[Dict[str, Any]]: def get_server(self, name: str) -> Optional[Dict[str, Any]]: response = self._request("GET", f"/servers/{name}") - if response.status_code == requests.codes.not_found: + if response.status_code == httpx2.codes.not_found: return None data = _response_data(response) server = data.get("server") @@ -162,25 +167,23 @@ def get_server(self, name: str) -> Optional[Dict[str, Any]]: def delete_server(self, name: str) -> None: """Delete a server, treating a missing server as success (idempotent).""" response = self._request("DELETE", f"/servers/{name}") - if response.status_code == requests.codes.not_found: + if response.status_code == httpx2.codes.not_found: logger.debug("Seeweb server %s already deleted", name) return _response_data(response) -def _response_data( - response: requests.Response, *, capacity_errors: bool = False -) -> Dict[str, Any]: +def _response_data(response: httpx2.Response, *, capacity_errors: bool = False) -> Dict[str, Any]: try: data = response.json() - except requests.JSONDecodeError as e: - if not response.ok: + except ValueError as e: + if response.is_error: raise BackendError(_response_message(response)) from e raise BackendError("Seeweb API returned a non-JSON response") from e if not isinstance(data, dict): raise BackendError("Seeweb API returned an invalid response") status = str(data.get("status", "ok")).lower() - if not response.ok or status not in {"ok", "success"}: + if response.is_error or status not in {"ok", "success"}: message = _response_message(response, data) if capacity_errors and _is_capacity_error(message): raise NoCapacityError(message) @@ -188,16 +191,16 @@ def _response_data( return data -def _raise_api_error(response: requests.Response) -> None: +def _raise_api_error(response: httpx2.Response) -> None: _response_data(response) -def _response_message(response: requests.Response, data: Optional[Dict[str, Any]] = None) -> str: +def _response_message(response: httpx2.Response, data: Optional[Dict[str, Any]] = None) -> str: if data is None: try: parsed = response.json() data = parsed if isinstance(parsed, dict) else None - except requests.JSONDecodeError: + except ValueError: data = None if data is not None: for field in ("message", "error", "detail"): diff --git a/src/dstack/_internal/core/backends/seeweb/compute.py b/src/dstack/_internal/core/backends/seeweb/compute.py index 48fa889eb..cf8105bb2 100644 --- a/src/dstack/_internal/core/backends/seeweb/compute.py +++ b/src/dstack/_internal/core/backends/seeweb/compute.py @@ -67,6 +67,9 @@ def __init__(self, config: SeewebConfig): self.config = config self.api_client = SeewebApiClient(config.creds.api_token) + def close(self) -> None: + self.api_client.close() + def _make_catalog(self) -> gpuhunt.Catalog: # Seeweb pricing requires auth, so query the provider live with the project's token # (like the vastai/jarvislabs backends) instead of relying on the published catalog. diff --git a/src/dstack/_internal/core/backends/vultr/api_client.py b/src/dstack/_internal/core/backends/vultr/api_client.py index 584cc9808..ace948b00 100644 --- a/src/dstack/_internal/core/backends/vultr/api_client.py +++ b/src/dstack/_internal/core/backends/vultr/api_client.py @@ -1,10 +1,10 @@ import base64 from typing import Any, Optional -import requests -from requests import Response +import httpx2 from dstack._internal.core.errors import BackendError, BackendInvalidCredentialsError +from dstack._internal.utils.http import HTTPClient API_URL = "https://api.vultr.com/v2" @@ -12,6 +12,10 @@ class VultrApiClient: def __init__(self, api_key: str): self.api_key = api_key + self._client = HTTPClient(follow_redirects=True) + + def close(self) -> None: + self._client.close() def validate_api_key(self) -> bool: try: @@ -90,9 +94,9 @@ def terminate_instance(self, instance_id: str, plan_type: str): endpoint = f"/instances/{instance_id}" self._make_request("DELETE", endpoint) - def _make_request(self, method: str, path: str, data: Any = None) -> Response: + def _make_request(self, method: str, path: str, data: Any = None) -> httpx2.Response: try: - response = requests.request( + response = self._client.request( method=method, url=API_URL + path, json=data, @@ -101,16 +105,16 @@ def _make_request(self, method: str, path: str, data: Any = None) -> Response: ) response.raise_for_status() return response - except requests.HTTPError as e: - if e.response is not None and e.response.status_code in ( - requests.codes.forbidden, - requests.codes.unauthorized, + except httpx2.HTTPStatusError as e: + if e.response.status_code in ( + httpx2.codes.forbidden, + httpx2.codes.unauthorized, ): raise BackendInvalidCredentialsError(e.response.text) - if e.response is not None and e.response.status_code in ( - requests.codes.bad_request, - requests.codes.internal_server_error, - requests.codes.not_found, + if e.response.status_code in ( + httpx2.codes.bad_request, + httpx2.codes.internal_server_error, + httpx2.codes.not_found, ): raise BackendError(e.response.text) raise diff --git a/src/dstack/_internal/core/backends/vultr/compute.py b/src/dstack/_internal/core/backends/vultr/compute.py index 1c3923dbb..382daaf64 100644 --- a/src/dstack/_internal/core/backends/vultr/compute.py +++ b/src/dstack/_internal/core/backends/vultr/compute.py @@ -3,7 +3,7 @@ from typing import List, Optional import gpuhunt -import requests +import httpx2 from gpuhunt.providers.vultr import VultrProvider from dstack._internal.core.backends.base.backend import Compute @@ -53,6 +53,9 @@ def __init__(self, config: VultrConfig): VultrProvider(api_key=config.creds.api_key, regions=config.regions) ) + def close(self) -> None: + self.api_client.close() + def get_all_offers_with_availability( self, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: @@ -126,8 +129,8 @@ def terminate_instance( plan_type = json.loads(backend_data)["plan_type"] try: self.api_client.terminate_instance(instance_id=instance_id, plan_type=plan_type) - except requests.HTTPError as e: - raise BackendError(e.response.text if e.response is not None else str(e)) + except httpx2.HTTPStatusError as e: + raise BackendError(e.response.text) def update_provisioning_data( self, diff --git a/src/tests/_internal/core/backends/cloudrift/test_api_client.py b/src/tests/_internal/core/backends/cloudrift/test_api_client.py index 0914b475c..5899e06a5 100644 --- a/src/tests/_internal/core/backends/cloudrift/test_api_client.py +++ b/src/tests/_internal/core/backends/cloudrift/test_api_client.py @@ -1,5 +1,5 @@ +import httpx2 import pytest -import requests from dstack._internal.core.backends.cloudrift.api_client import ( CLOUDRIFT_SERVER_ADDRESS, @@ -49,30 +49,27 @@ class TestRiftClient: ("instances/terminate", {"terminated": []}), ], ) - def test_uses_current_production_protocol(self, requests_mock, endpoint, data): + def test_uses_current_production_protocol(self, http_mock, endpoint, data): # CloudRift rejects the old pin on provisioning endpoints, even though # auth and instance-type discovery still accept it. - requests_mock.post( - f"{API_ROOT}/{endpoint}", - additional_matcher=lambda request: request.json()["version"] == "2026-10-12", - json=_response(data), - ) + http_mock.post(f"{API_ROOT}/{endpoint}", json=_response(data)) assert RiftClient("test-key")._make_request(endpoint, {}) == data - assert requests_mock.last_request.headers["X-API-Key"] == "test-key" + assert http_mock.last_request.json()["version"] == "2026-10-12" + assert http_mock.last_request.headers["X-API-Key"] == "test-key" @pytest.mark.parametrize("status_code", [401, 403]) - def test_rejects_invalid_credentials(self, requests_mock, status_code): - requests_mock.post(f"{API_ROOT}/auth/me", status_code=status_code, text="invalid key") + def test_rejects_invalid_credentials(self, http_mock, status_code): + http_mock.post(f"{API_ROOT}/auth/me", status_code=status_code, text="invalid key") assert RiftClient("test-key").validate_api_key() is False with pytest.raises(BackendInvalidCredentialsError, match="invalid key"): RiftClient("test-key")._make_request("auth/me") - def test_preserves_http_errors(self, requests_mock): - requests_mock.post(f"{API_ROOT}/recipes/list", status_code=400, text="unsupported version") + def test_preserves_http_errors(self, http_mock): + http_mock.post(f"{API_ROOT}/recipes/list", status_code=400, text="unsupported version") - with pytest.raises(requests.HTTPError) as exc_info: + with pytest.raises(httpx2.HTTPStatusError) as exc_info: RiftClient("test-key").list_recipes() assert exc_info.value.response is not None @@ -81,9 +78,9 @@ def test_preserves_http_errors(self, requests_mock): class TestRiftClientDeployInstance: @pytest.mark.parametrize("gpu_vendor", ["nvidia", "amd"]) - def test_discovers_image_and_rents_vm(self, requests_mock, gpu_vendor): - requests_mock.post(f"{API_ROOT}/recipes/list", json=_response(_recipes())) - requests_mock.post( + def test_discovers_image_and_rents_vm(self, http_mock, gpu_vendor): + http_mock.post(f"{API_ROOT}/recipes/list", json=_response(_recipes())) + http_mock.post( f"{API_ROOT}/instances/rent", json=_response({"instance_ids": ["instance-id"]}, version="2026-09-09"), ) @@ -97,7 +94,7 @@ def test_discovers_image_and_rents_vm(self, requests_mock, gpu_vendor): ) assert instance_ids == ["instance-id"] - assert requests_mock.last_request.json() == { + assert http_mock.last_request.json() == { "version": "2026-10-12", "data": { "config": { @@ -117,38 +114,38 @@ def test_discovers_image_and_rents_vm(self, requests_mock, gpu_vendor): }, } - def test_does_not_rent_without_suitable_image(self, requests_mock): - requests_mock.post(f"{API_ROOT}/recipes/list", json=_response({"groups": []})) + def test_does_not_rent_without_suitable_image(self, http_mock): + http_mock.post(f"{API_ROOT}/recipes/list", json=_response({"groups": []})) with pytest.raises(BackendError, match="No suitable VM image"): RiftClient("test-key").deploy_instance("type.1", "region", [], "start-shim") - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 class TestRiftClientListInstances: - def test_selects_active_statuses_and_requests_connection_info(self, requests_mock): + def test_selects_active_statuses_and_requests_connection_info(self, http_mock): instances = [{"id": "instance-id", "host_address": "192.0.2.1"}] - requests_mock.post( + http_mock.post( f"{API_ROOT}/instances/list", json=_response({"instances": instances}, version="2026-08-05"), ) assert RiftClient("test-key").list_instances() == instances - assert requests_mock.last_request.json()["data"] == { + assert http_mock.last_request.json()["data"] == { "selector": {"ByStatus": {"statuses": ["Initializing", "Active", "Deactivating"]}}, "mask": {"with_connection_info": True, "with_credentials": True}, } @pytest.mark.parametrize("instance_ids", [[], ["instance-id", "other-id"]]) - def test_selects_requested_ids(self, requests_mock, instance_ids): - requests_mock.post(f"{API_ROOT}/instances/list", json=_response({"instances": []})) + def test_selects_requested_ids(self, http_mock, instance_ids): + http_mock.post(f"{API_ROOT}/instances/list", json=_response({"instances": []})) assert RiftClient("test-key").list_instances(instance_ids) == [] - assert requests_mock.last_request.json()["data"]["selector"] == {"ById": instance_ids} + assert http_mock.last_request.json()["data"]["selector"] == {"ById": instance_ids} @pytest.mark.parametrize("found", [True, False]) - def test_gets_instance_by_id_with_connection_info(self, requests_mock, found): + def test_gets_instance_by_id_with_connection_info(self, http_mock, found): instance = { "id": "instance-id", "node_mode": "VirtualMachine", @@ -156,7 +153,7 @@ def test_gets_instance_by_id_with_connection_info(self, requests_mock, found): "port_mappings": [[22, 57001]], "virtual_machines": [{"ready": True}], } - requests_mock.post( + http_mock.post( f"{API_ROOT}/instances/list", json=_response({"instances": [instance] if found else []}, version="2026-08-05"), ) @@ -164,29 +161,29 @@ def test_gets_instance_by_id_with_connection_info(self, requests_mock, found): assert RiftClient("test-key").get_instance_by_id("instance-id") == ( instance if found else None ) - assert requests_mock.last_request.json()["data"] == { + assert http_mock.last_request.json()["data"] == { "selector": {"ById": ["instance-id"]}, "mask": {"with_connection_info": True, "with_credentials": True}, } class TestRiftClientTerminateInstance: - def test_terminates_requested_instance(self, requests_mock): - requests_mock.post( + def test_terminates_requested_instance(self, http_mock): + http_mock.post( f"{API_ROOT}/instances/terminate", json=_response({"terminated": [{"id": "instance-id"}]}, version="2026-08-05"), ) assert RiftClient("test-key").terminate_instance("instance-id") is True - assert requests_mock.last_request.json() == { + assert http_mock.last_request.json() == { "version": "2026-10-12", "data": {"selector": {"ById": ["instance-id"]}}, } @pytest.mark.parametrize("status", [None, "Inactive", "Deactivating", "Active"]) - def test_checks_already_terminated_instance(self, requests_mock, status): - requests_mock.post(f"{API_ROOT}/instances/terminate", json=_response({"terminated": []})) - requests_mock.post( + def test_checks_already_terminated_instance(self, http_mock, status): + http_mock.post(f"{API_ROOT}/instances/terminate", json=_response({"terminated": []})) + http_mock.post( f"{API_ROOT}/instances/list", json=_response({"instances": [{"status": status}] if status else []}), ) diff --git a/src/tests/_internal/core/backends/daytona/test_api_client.py b/src/tests/_internal/core/backends/daytona/test_api_client.py index a3198c6a8..d7e4568f4 100644 --- a/src/tests/_internal/core/backends/daytona/test_api_client.py +++ b/src/tests/_internal/core/backends/daytona/test_api_client.py @@ -1,5 +1,5 @@ +import httpx2 import pytest -import requests from dstack._internal.core.backends.daytona.api_client import ( API_URL, @@ -12,19 +12,17 @@ class TestDaytonaAPIClient: - def test_identity_uses_bearer_auth(self, requests_mock): - requests_mock.get( - f"{API_URL}/api-keys/current", json={"organizationId": "organization-id"} - ) + def test_identity_uses_bearer_auth(self, http_mock): + http_mock.get(f"{API_URL}/api-keys/current", json={"organizationId": "organization-id"}) identity = DaytonaAPIClient("test-api-key").get_current_api_key() assert identity["organizationId"] == "organization-id" - assert requests_mock.last_request.headers["Authorization"] == "Bearer test-api-key" - assert requests_mock.last_request.timeout == 30 + assert http_mock.last_request.headers["Authorization"] == "Bearer test-api-key" + assert http_mock.last_request.timeout["read"] == 30 - def test_unauthorized_maps_to_invalid_credentials(self, requests_mock): - requests_mock.get(f"{API_URL}/api-keys/current", status_code=401) + def test_unauthorized_maps_to_invalid_credentials(self, http_mock): + http_mock.get(f"{API_URL}/api-keys/current", status_code=401) with pytest.raises(BackendInvalidCredentialsError) as exc: DaytonaAPIClient("bad-key").get_current_api_key() @@ -39,20 +37,20 @@ def test_unauthorized_maps_to_invalid_credentials(self, requests_mock): (503, "Service unavailable"), ], ) - def test_http_errors_preserve_status_and_reason(self, requests_mock, status, message): - requests_mock.post(f"{API_URL}/sandbox", status_code=status, json={"message": message}) + def test_http_errors_preserve_status_and_reason(self, http_mock, status, message): + http_mock.post(f"{API_URL}/sandbox", status_code=status, json={"message": message}) with pytest.raises(DaytonaAPIError, match=message) as exc: DaytonaAPIClient("test-api-key").create_sandbox({"name": "test"}) assert exc.value.status_code == status assert not isinstance(exc.value, NoCapacityError) - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 - @pytest.mark.parametrize("error", [requests.ReadTimeout, requests.ConnectionError]) - def test_network_errors_preserve_cause_without_retrying(self, requests_mock, error): + @pytest.mark.parametrize("error", [httpx2.ReadTimeout, httpx2.ConnectError]) + def test_network_errors_preserve_cause_without_retrying(self, http_mock, error): cause = error("Connection failed") - requests_mock.post(f"{API_URL}/sandbox", exc=cause) + http_mock.post(f"{API_URL}/sandbox", exc=cause) client = DaytonaAPIClient("test-api-key") with pytest.raises(DaytonaAPIError) as exc: @@ -60,10 +58,10 @@ def test_network_errors_preserve_cause_without_retrying(self, requests_mock, err assert exc.value.__cause__ is cause assert exc.value.status_code is None - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 - def test_error_response_redacts_api_key(self, requests_mock): - requests_mock.get( + def test_error_response_redacts_api_key(self, http_mock): + http_mock.get( f"{API_URL}/api-keys/current", status_code=403, json={"message": "Denied for Bearer secret-api-key"}, @@ -72,8 +70,8 @@ def test_error_response_redacts_api_key(self, requests_mock): with pytest.raises(DaytonaAPIError, match="Denied for Bearer \\[redacted\\]"): DaytonaAPIClient("secret-api-key").get_current_api_key() - def test_non_json_error_omits_response_body(self, requests_mock): - requests_mock.get( + def test_non_json_error_omits_response_body(self, http_mock): + http_mock.get( f"{API_URL}/api-keys/current", status_code=502, text="gateway HTML with credentials" ) @@ -82,8 +80,8 @@ def test_non_json_error_omits_response_body(self, requests_mock): assert str(exc.value) == "Daytona API returned HTTP 502" - def test_redirect_is_not_followed(self, requests_mock): - requests_mock.get( + def test_redirect_is_not_followed(self, http_mock): + http_mock.get( f"{API_URL}/api-keys/current", status_code=302, headers={"Location": "https://untrusted.example/identity"}, @@ -93,13 +91,13 @@ def test_redirect_is_not_followed(self, requests_mock): DaytonaAPIClient("test-api-key").get_current_api_key() assert exc.value.status_code == 302 - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 - def test_get_sandbox_accepts_id_or_name_and_returns_none_only_for_404(self, requests_mock): - requests_mock.get(f"{API_URL}/sandbox/sandbox-id", json={"id": "sandbox-id"}) - requests_mock.get(f"{API_URL}/sandbox/job-name", json={"id": "sandbox-id"}) - requests_mock.get(f"{API_URL}/sandbox/missing", status_code=404) - requests_mock.get(f"{API_URL}/sandbox/forbidden", status_code=403) + def test_get_sandbox_accepts_id_or_name_and_returns_none_only_for_404(self, http_mock): + http_mock.get(f"{API_URL}/sandbox/sandbox-id", json={"id": "sandbox-id"}) + http_mock.get(f"{API_URL}/sandbox/job-name", json={"id": "sandbox-id"}) + http_mock.get(f"{API_URL}/sandbox/missing", status_code=404) + http_mock.get(f"{API_URL}/sandbox/forbidden", status_code=403) client = DaytonaAPIClient("test-api-key") assert client.get_sandbox("sandbox-id") == {"id": "sandbox-id"} @@ -108,18 +106,18 @@ def test_get_sandbox_accepts_id_or_name_and_returns_none_only_for_404(self, requ with pytest.raises(DaytonaAPIError): client.get_sandbox("forbidden") - def test_volume_create_lookup_and_deleted_tombstone(self, requests_mock): + def test_volume_create_lookup_and_deleted_tombstone(self, http_mock): pending = {"id": "volume-id", "state": "pending_create"} deleted = {"id": "volume-id", "state": "deleted"} - requests_mock.post(f"{API_URL}/volumes", json=pending) - requests_mock.get(f"{API_URL}/volumes/by-name/volume-name", json=pending) - requests_mock.get(f"{API_URL}/volumes/volume-id", json=deleted) - requests_mock.get(f"{API_URL}/volumes/missing", status_code=404) - requests_mock.get(f"{API_URL}/volumes/by-name/missing", status_code=404) + http_mock.post(f"{API_URL}/volumes", json=pending) + http_mock.get(f"{API_URL}/volumes/by-name/volume-name", json=pending) + http_mock.get(f"{API_URL}/volumes/volume-id", json=deleted) + http_mock.get(f"{API_URL}/volumes/missing", status_code=404) + http_mock.get(f"{API_URL}/volumes/by-name/missing", status_code=404) client = DaytonaAPIClient("test-api-key") assert client.create_volume("volume-name") == pending - assert requests_mock.last_request.json() == {"name": "volume-name"} + assert http_mock.last_request.json() == {"name": "volume-name"} assert client.get_volume_by_name("volume-name") == pending assert client.get_volume("volume-id") == deleted assert client.get_volume("missing") is None @@ -133,8 +131,8 @@ def test_volume_create_lookup_and_deleted_tombstone(self, requests_mock): ("delete_volume", "/volumes/resource-id", 404), ], ) - def test_delete_endpoints_are_idempotent(self, requests_mock, method, path, status): - requests_mock.delete(API_URL + path, status_code=status) + def test_delete_endpoints_are_idempotent(self, http_mock, method, path, status): + http_mock.delete(API_URL + path, status_code=status) getattr(DaytonaAPIClient("test-api-key"), method)("resource-id") @@ -143,42 +141,42 @@ def test_delete_endpoints_are_idempotent(self, requests_mock, method, path, stat [ ("delete_sandbox", "/sandbox/resource-id", {"status_code": 503}), ("delete_registry", "/docker-registry/resource-id", {"status_code": 429}), - ("delete_volume", "/volumes/resource-id", {"exc": requests.ReadTimeout}), + ("delete_volume", "/volumes/resource-id", {"exc": httpx2.ReadTimeout}), ], ) - def test_delete_retries_transient_errors(self, requests_mock, mocker, method, path, failure): + def test_delete_retries_transient_errors(self, http_mock, mocker, method, path, failure): sleep = mocker.patch("dstack._internal.core.backends.daytona.api_client.time.sleep") - requests_mock.delete(API_URL + path, [failure, {"status_code": 404}]) + http_mock.delete(API_URL + path, [failure, {"status_code": 404}]) getattr(DaytonaAPIClient("test-api-key"), method)("resource-id") - assert requests_mock.call_count == 2 + assert http_mock.call_count == 2 sleep.assert_called_once_with(1) - def test_delete_stops_retrying_after_three_attempts(self, requests_mock, mocker): + def test_delete_stops_retrying_after_three_attempts(self, http_mock, mocker): sleep = mocker.patch("dstack._internal.core.backends.daytona.api_client.time.sleep") - requests_mock.delete(f"{API_URL}/docker-registry/registry-id", status_code=503) + http_mock.delete(f"{API_URL}/docker-registry/registry-id", status_code=503) with pytest.raises(DaytonaAPIError) as exc: DaytonaAPIClient("test-api-key").delete_registry("registry-id") assert exc.value.status_code == 503 - assert requests_mock.call_count == 3 + assert http_mock.call_count == 3 assert [call.args[0] for call in sleep.call_args_list] == [1, 2] - def test_delete_does_not_retry_permission_errors(self, requests_mock, mocker): + def test_delete_does_not_retry_permission_errors(self, http_mock, mocker): sleep = mocker.patch("dstack._internal.core.backends.daytona.api_client.time.sleep") - requests_mock.delete(f"{API_URL}/docker-registry/registry-id", status_code=403) + http_mock.delete(f"{API_URL}/docker-registry/registry-id", status_code=403) with pytest.raises(DaytonaAPIError) as exc: DaytonaAPIClient("test-api-key").delete_registry("registry-id") assert exc.value.status_code == 403 - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 sleep.assert_not_called() - def test_toolbox_url_includes_sandbox_id(self, requests_mock): - requests_mock.get( + def test_toolbox_url_includes_sandbox_id(self, http_mock): + http_mock.get( f"{API_URL}/sandbox/sandbox-id/toolbox-proxy-url", json={"url": "https://proxy.app.daytona.io/toolbox/"}, ) @@ -196,47 +194,45 @@ def test_toolbox_url_includes_sandbox_id(self, requests_mock): "https://proxy.app.daytona.io:8443/toolbox", ], ) - def test_toolbox_rejects_untrusted_url_before_sending_credentials(self, requests_mock, url): + def test_toolbox_rejects_untrusted_url_before_sending_credentials(self, http_mock, url): with pytest.raises(DaytonaAPIError, match="invalid toolbox proxy URL"): DaytonaAPIClient("test-api-key").get_session(url, "runner") - assert requests_mock.call_count == 0 + assert http_mock.call_count == 0 - def test_session_creation_and_async_command(self, requests_mock): - requests_mock.post(f"{TOOLBOX_URL}/process/session", status_code=201) - requests_mock.post( - f"{TOOLBOX_URL}/process/session/runner/exec", json={"cmdId": "command-id"} - ) + def test_session_creation_and_async_command(self, http_mock): + http_mock.post(f"{TOOLBOX_URL}/process/session", status_code=201) + http_mock.post(f"{TOOLBOX_URL}/process/session/runner/exec", json={"cmdId": "command-id"}) client = DaytonaAPIClient("test-api-key") client.create_session(TOOLBOX_URL, "runner") command = client.execute_session_command(TOOLBOX_URL, "runner", "/tmp/dstack-runner start") - assert requests_mock.request_history[0].json() == {"sessionId": "runner"} - assert requests_mock.last_request.json() == { + assert http_mock.request_history[0].json() == {"sessionId": "runner"} + assert http_mock.last_request.json() == { "command": "/tmp/dstack-runner start", "runAsync": True, } - assert requests_mock.last_request.headers["Authorization"] == "Bearer test-api-key" + assert http_mock.last_request.headers["Authorization"] == "Bearer test-api-key" assert command == {"cmdId": "command-id"} - def test_missing_session(self, requests_mock): - requests_mock.get(f"{TOOLBOX_URL}/process/session/runner", status_code=404) + def test_missing_session(self, http_mock): + http_mock.get(f"{TOOLBOX_URL}/process/session/runner", status_code=404) client = DaytonaAPIClient("test-api-key") assert client.get_session(TOOLBOX_URL, "runner") is None - def test_ssh_access_preserves_explicit_long_lifetime(self, requests_mock): + def test_ssh_access_preserves_explicit_long_lifetime(self, http_mock): access = { "token": "ssh-access-token", "sshCommand": "ssh -p 2222 ssh-access-token@ssh.app.daytona.io", "expiresAt": "2027-09-28T00:00:00Z", } - requests_mock.post(f"{API_URL}/sandbox/sandbox-id/ssh-access", json=access) + http_mock.post(f"{API_URL}/sandbox/sandbox-id/ssh-access", json=access) result = DaytonaAPIClient("test-api-key").create_ssh_access( "sandbox-id", expires_in_minutes=365 * 24 * 60 ) assert result == access - assert requests_mock.last_request.qs == {"expiresinminutes": ["525600"]} + assert http_mock.last_request.qs == {"expiresInMinutes": ["525600"]} diff --git a/src/tests/_internal/core/backends/daytona/test_compute.py b/src/tests/_internal/core/backends/daytona/test_compute.py index 8fcefedcf..fd1996435 100644 --- a/src/tests/_internal/core/backends/daytona/test_compute.py +++ b/src/tests/_internal/core/backends/daytona/test_compute.py @@ -702,7 +702,7 @@ def test_deletion_is_idempotent_while_provider_is_destroying(self, compute): class TestGetOffersByRequirements: - def test_offer_queries_use_only_api_key_accessible_endpoints(self, requests_mock): + def test_offer_queries_use_only_api_key_accessible_endpoints(self, http_mock): # Organization details require dashboard authentication, even for a valid API key. # No organization-details mock is registered so using that endpoint fails this test. paths = [ @@ -710,9 +710,9 @@ def test_offer_queries_use_only_api_key_accessible_endpoints(self, requests_mock "/organizations/org-id/usage", "/organizations/org-id/available-sandbox-classes", ] - requests_mock.get(API_URL + paths[0], json={"organizationId": "org-id"}) - requests_mock.get(API_URL + paths[1], json={"regionUsage": [_cpu_usage(), _gpu_usage()]}) - requests_mock.get( + http_mock.get(API_URL + paths[0], json={"organizationId": "org-id"}) + http_mock.get(API_URL + paths[1], json={"regionUsage": [_cpu_usage(), _gpu_usage()]}) + http_mock.get( API_URL + paths[2], json=[ {"regionId": "us", "sandboxClass": "container", "gpuAvailable": False}, @@ -724,12 +724,12 @@ def test_offer_queries_use_only_api_key_accessible_endpoints(self, requests_mock offers = _offers(compute, _item(), _item(gpu=True)) assert [offer.availability for offer in offers] == [InstanceAvailability.AVAILABLE] * 2 - assert [request.url for request in requests_mock.request_history] == [ + assert [request.url for request in http_mock.request_history] == [ API_URL + path for path in paths ] assert all( request.headers["Authorization"] == "Bearer test-api-key" - for request in requests_mock.request_history + for request in http_mock.request_history ) def test_organization_id_is_cached_but_quotas_are_refreshed(self, compute): diff --git a/src/tests/_internal/core/backends/daytona/test_configurator.py b/src/tests/_internal/core/backends/daytona/test_configurator.py index 8e272dd37..21488b88c 100644 --- a/src/tests/_internal/core/backends/daytona/test_configurator.py +++ b/src/tests/_internal/core/backends/daytona/test_configurator.py @@ -46,10 +46,8 @@ def test_validate_config_accepts_only_required_permissions(self, client): (["delete:sandboxes", "read:limits"], "write:sandboxes"), ], ) - def test_validate_config_reports_missing_permissions( - self, requests_mock, permissions, missing - ): - requests_mock.get(f"{API_URL}/api-keys/current", json={"permissions": permissions}) + def test_validate_config_reports_missing_permissions(self, http_mock, permissions, missing): + http_mock.get(f"{API_URL}/api-keys/current", json={"permissions": permissions}) config = DaytonaBackendConfigWithCreds(creds=DaytonaCreds(api_key="test-key")) with pytest.raises(BackendInvalidCredentialsError) as exc: @@ -57,7 +55,7 @@ def test_validate_config_reports_missing_permissions( assert exc.value.msg == f"Daytona API key is missing permissions: {missing}" assert exc.value.fields == [["creds", "api_key"]] - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 def test_validate_config_accepts_gpu_and_discovered_cpu_regions(self, client): config = DaytonaBackendConfigWithCreds( diff --git a/src/tests/_internal/core/backends/hotaisle/test_api_client.py b/src/tests/_internal/core/backends/hotaisle/test_api_client.py index c69c969d3..74b5a312e 100644 --- a/src/tests/_internal/core/backends/hotaisle/test_api_client.py +++ b/src/tests/_internal/core/backends/hotaisle/test_api_client.py @@ -1,5 +1,5 @@ +import httpx2 import pytest -import requests from dstack._internal.core.backends.hotaisle.api_client import API_URL, HotAisleAPIClient from dstack._internal.core.errors import BackendError, NoCapacityError @@ -13,15 +13,15 @@ def _client() -> HotAisleAPIClient: class TestReserveBareMetalServer: - def test_posts_specs_and_description(self, requests_mock): - requests_mock.post(BARE_METAL_URL, json={"deployment_id": "deployment-id"}) + def test_posts_specs_and_description(self, http_mock): + http_mock.post(BARE_METAL_URL, json={"deployment_id": "deployment-id"}) server_data = _client().reserve_bare_metal_server( specs={"cpu_cores": 104}, description="test-instance" ) assert server_data == {"deployment_id": "deployment-id"} - assert requests_mock.last_request.json() == { + assert http_mock.last_request.json() == { "specs": {"cpu_cores": 104}, "description": "test-instance", } @@ -30,47 +30,47 @@ def test_posts_specs_and_description(self, requests_mock): ("status_code", "text"), [(403, "tenant limit exceeded"), (404, "no available servers")], ) - def test_raises_no_capacity(self, requests_mock, status_code, text): - requests_mock.post(BARE_METAL_URL, status_code=status_code, text=text) + def test_raises_no_capacity(self, http_mock, status_code, text): + http_mock.post(BARE_METAL_URL, status_code=status_code, text=text) with pytest.raises(NoCapacityError, match=text): _client().reserve_bare_metal_server(specs={}, description="test-instance") - def test_raises_on_other_errors(self, requests_mock): - requests_mock.post(BARE_METAL_URL, status_code=402) + def test_raises_on_other_errors(self, http_mock): + http_mock.post(BARE_METAL_URL, status_code=402) - with pytest.raises(requests.HTTPError): + with pytest.raises(httpx2.HTTPStatusError): _client().reserve_bare_metal_server(specs={}, description="test-instance") class TestReleaseBareMetalServer: - def test_forces_release(self, requests_mock): - requests_mock.delete(SERVER_URL, status_code=204) + def test_forces_release(self, http_mock): + http_mock.delete(SERVER_URL, status_code=204) _client().release_bare_metal_server("deployment-id") - assert requests_mock.last_request.qs == {"force": ["true"]} + assert http_mock.last_request.qs == {"force": ["true"]} - def test_releases_without_force(self, requests_mock): - requests_mock.delete(SERVER_URL, status_code=204) + def test_releases_without_force(self, http_mock): + http_mock.delete(SERVER_URL, status_code=204) _client().release_bare_metal_server("deployment-id", force=False) - assert requests_mock.last_request.qs == {} + assert http_mock.last_request.qs == {} - def test_raises_if_refused_without_force(self, requests_mock): - requests_mock.delete(SERVER_URL, status_code=400, text="minimum usage requirement") + def test_raises_if_refused_without_force(self, http_mock): + http_mock.delete(SERVER_URL, status_code=400, text="minimum usage requirement") with pytest.raises(BackendError, match="minimum usage requirement"): _client().release_bare_metal_server("deployment-id", force=False) - def test_ignores_missing_server(self, requests_mock): - requests_mock.delete(SERVER_URL, status_code=404) + def test_ignores_missing_server(self, http_mock): + http_mock.delete(SERVER_URL, status_code=404) _client().release_bare_metal_server("deployment-id") - def test_raises_on_other_errors(self, requests_mock): - requests_mock.delete(SERVER_URL, status_code=400) + def test_raises_on_other_errors(self, http_mock): + http_mock.delete(SERVER_URL, status_code=400) - with pytest.raises(requests.HTTPError): + with pytest.raises(httpx2.HTTPStatusError): _client().release_bare_metal_server("deployment-id") diff --git a/src/tests/_internal/core/backends/jarvislabs/test_api_client.py b/src/tests/_internal/core/backends/jarvislabs/test_api_client.py index 9fdf48724..3edcff0da 100644 --- a/src/tests/_internal/core/backends/jarvislabs/test_api_client.py +++ b/src/tests/_internal/core/backends/jarvislabs/test_api_client.py @@ -1,5 +1,5 @@ +import httpx2 import pytest -import requests from gpuhunt.providers.jarvislabs import API_URL from dstack._internal.core.backends.jarvislabs.api_client import ( @@ -9,65 +9,65 @@ from dstack._internal.core.errors import BackendError, BackendInvalidCredentialsError -def test_validate_api_key_returns_false_on_unauthorized(requests_mock): - requests_mock.get(f"{API_URL}/users/user_info", status_code=401) +def test_validate_api_key_returns_false_on_unauthorized(http_mock): + http_mock.get(f"{API_URL}/users/user_info", status_code=401) assert JarvisLabsAPIClient("bad").validate_api_key() is False -def test_get_user_info_raises_invalid_credentials_on_forbidden(requests_mock): - requests_mock.get(f"{API_URL}/users/user_info", status_code=403) +def test_get_user_info_raises_invalid_credentials_on_forbidden(http_mock): + http_mock.get(f"{API_URL}/users/user_info", status_code=403) with pytest.raises(BackendInvalidCredentialsError): JarvisLabsAPIClient("bad").get_user_info() -def test_make_request_wraps_request_errors(requests_mock): - requests_mock.get( +def test_make_request_wraps_request_errors(http_mock): + http_mock.get( f"{API_URL}/users/user_info", - exc=requests.ConnectTimeout("timed out"), + exc=httpx2.ConnectTimeout("timed out"), ) with pytest.raises(BackendError, match="JarvisLabs request failed"): JarvisLabsAPIClient("token").get_user_info() -def test_get_user_info_rejects_non_json_success_response(requests_mock): - requests_mock.get(f"{API_URL}/users/user_info", text="ok") +def test_get_user_info_rejects_non_json_success_response(http_mock): + http_mock.get(f"{API_URL}/users/user_info", text="ok") with pytest.raises(BackendError, match="Unexpected non-JSON JarvisLabs response"): JarvisLabsAPIClient("token").get_user_info() -def test_add_ssh_key_if_needed_reuses_existing_key(requests_mock): +def test_add_ssh_key_if_needed_reuses_existing_key(http_mock): public_key = "ssh-rsa AAAA test-comment" - requests_mock.get( + http_mock.get( f"{API_URL}/ssh/", json=[{"ssh_key": "ssh-rsa AAAA another-comment", "key_name": "existing"}], ) JarvisLabsAPIClient("token").add_ssh_key_if_needed(public_key) - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 -def test_add_ssh_key_if_needed_adds_missing_key(requests_mock): +def test_add_ssh_key_if_needed_adds_missing_key(http_mock): public_key = "ssh-rsa AAAA test-comment" - requests_mock.get(f"{API_URL}/ssh/", json=[]) - requests_mock.post(f"{API_URL}/ssh/", json={"success": True}) + http_mock.get(f"{API_URL}/ssh/", json=[]) + http_mock.post(f"{API_URL}/ssh/", json={"success": True}) JarvisLabsAPIClient("token").add_ssh_key_if_needed(public_key) - assert requests_mock.last_request.json() == { + assert http_mock.last_request.json() == { "ssh_key": public_key, "key_name": "dstack-36deb09319b2204c", } -def test_create_ssh_key_adds_key_and_returns_created_key_id(requests_mock): +def test_create_ssh_key_adds_key_and_returns_created_key_id(http_mock): public_key = "ssh-rsa AAAA test-comment" - requests_mock.post(f"{API_URL}/ssh/", json={"success": True}) - requests_mock.get( + http_mock.post(f"{API_URL}/ssh/", json={"success": True}) + http_mock.get( f"{API_URL}/ssh/", json=[ { @@ -84,15 +84,15 @@ def test_create_ssh_key_adds_key_and_returns_created_key_id(requests_mock): ) assert key_id == "key-id" - assert requests_mock.request_history[0].json() == { + assert http_mock.request_history[0].json() == { "ssh_key": public_key, "key_name": "dstack-test-0.key", } -def test_create_ssh_key_raises_if_created_key_id_is_missing(requests_mock): - requests_mock.post(f"{API_URL}/ssh/", json={"success": True}) - requests_mock.get(f"{API_URL}/ssh/", json=[]) +def test_create_ssh_key_raises_if_created_key_id_is_missing(http_mock): + http_mock.post(f"{API_URL}/ssh/", json={"success": True}) + http_mock.get(f"{API_URL}/ssh/", json=[]) with pytest.raises(BackendError, match="Failed to find created JarvisLabs SSH key"): JarvisLabsAPIClient("token").create_ssh_key( @@ -101,22 +101,22 @@ def test_create_ssh_key_raises_if_created_key_id_is_missing(requests_mock): ) -def test_delete_ssh_key_deletes_key(requests_mock): - requests_mock.delete(f"{API_URL}/ssh/key-id", json={"success": True}) +def test_delete_ssh_key_deletes_key(http_mock): + http_mock.delete(f"{API_URL}/ssh/key-id", json={"success": True}) JarvisLabsAPIClient("token").delete_ssh_key("key-id") - assert requests_mock.last_request.method == "DELETE" + assert http_mock.last_request.method == "DELETE" -def test_delete_ssh_key_ignores_missing_key(requests_mock): - requests_mock.delete(f"{API_URL}/ssh/key-id", status_code=404, json={"detail": "not found"}) +def test_delete_ssh_key_ignores_missing_key(http_mock): + http_mock.delete(f"{API_URL}/ssh/key-id", status_code=404, json={"detail": "not found"}) JarvisLabsAPIClient("token").delete_ssh_key("key-id") -def test_create_gpu_vm_posts_to_regional_vm_endpoint(requests_mock): - requests_mock.post( +def test_create_gpu_vm_posts_to_regional_vm_endpoint(http_mock): + http_mock.post( "https://backendn.jarvislabs.net/templates/vm/create", json={"machine_id": 123}, ) @@ -131,8 +131,8 @@ def test_create_gpu_vm_posts_to_regional_vm_endpoint(requests_mock): ) assert machine_id == "123" - assert requests_mock.last_request.headers["Authorization"] == "Bearer token" - assert requests_mock.last_request.json() == { + assert http_mock.last_request.headers["Authorization"] == "Bearer token" + assert http_mock.last_request.json() == { "gpu_type": "A100-80GB", "num_gpus": 1, "hdd": 250, @@ -149,8 +149,8 @@ def test_create_gpu_vm_posts_to_regional_vm_endpoint(requests_mock): } -def test_create_gpu_vm_posts_chennai_region_to_chennai_endpoint(requests_mock): - requests_mock.post( +def test_create_gpu_vm_posts_chennai_region_to_chennai_endpoint(http_mock): + http_mock.post( "https://backendc.jarvislabs.net/templates/vm/create", json={"machine_id": 123}, ) @@ -164,11 +164,11 @@ def test_create_gpu_vm_posts_chennai_region_to_chennai_endpoint(requests_mock): name="dstack-test", ) - assert requests_mock.last_request.json()["gpu_type"] == "RTX-PRO6000" - assert requests_mock.last_request.json()["region"] == "india-chennai-01" + assert http_mock.last_request.json()["gpu_type"] == "RTX-PRO6000" + assert http_mock.last_request.json()["region"] == "india-chennai-01" -def test_create_gpu_vm_rejects_unsupported_region(requests_mock): +def test_create_gpu_vm_rejects_unsupported_region(http_mock): with pytest.raises(BackendError, match="Unsupported JarvisLabs region"): JarvisLabsAPIClient("token").create_gpu_vm( gpu_type="H100", @@ -179,11 +179,11 @@ def test_create_gpu_vm_rejects_unsupported_region(requests_mock): name="dstack-test", ) - assert requests_mock.call_count == 0 + assert http_mock.call_count == 0 -def test_create_gpu_vm_sets_spot_flag(requests_mock): - requests_mock.post( +def test_create_gpu_vm_sets_spot_flag(http_mock): + http_mock.post( "https://backendn.jarvislabs.net/templates/vm/create", json={"machine_id": 123}, ) @@ -197,11 +197,11 @@ def test_create_gpu_vm_sets_spot_flag(requests_mock): name="dstack-spot", ) - assert requests_mock.last_request.json()["is_spot"] is True + assert http_mock.last_request.json()["is_spot"] is True -def test_create_cpu_vm_posts_to_regional_cpu_vm_endpoint(requests_mock): - requests_mock.post( +def test_create_cpu_vm_posts_to_regional_cpu_vm_endpoint(http_mock): + http_mock.post( "https://backendn.jarvislabs.net/templates/vm/cpu/create", json={"machine_id": 456}, ) @@ -215,7 +215,7 @@ def test_create_cpu_vm_posts_to_regional_cpu_vm_endpoint(requests_mock): ) assert machine_id == "456" - assert requests_mock.last_request.json() == { + assert http_mock.last_request.json() == { "num_cpus": 1, "vcpus": 4, "ram_gb": 16, @@ -227,8 +227,8 @@ def test_create_cpu_vm_posts_to_regional_cpu_vm_endpoint(requests_mock): } -def test_destroy_instance_uses_cpu_vm_endpoint_for_cpu_vm(requests_mock): - requests_mock.get( +def test_destroy_instance_uses_cpu_vm_endpoint_for_cpu_vm(http_mock): + http_mock.get( f"{API_URL}/users/fetch/456", json={ "success": True, @@ -240,14 +240,14 @@ def test_destroy_instance_uses_cpu_vm_endpoint_for_cpu_vm(requests_mock): }, }, ) - requests_mock.post( + http_mock.post( "https://backendn.jarvislabs.net/templates/vm/cpu/destroy", json={"success": True}, ) JarvisLabsAPIClient("token").destroy_instance(machine_id="456", region="india-noida-01") - assert requests_mock.last_request.qs == {"machine_id": ["456"]} + assert http_mock.last_request.qs == {"machine_id": ["456"]} def test_is_cpu_vm_requires_vm_template_and_cpu_gpu_type(): diff --git a/src/tests/_internal/core/backends/lium/test_api_client.py b/src/tests/_internal/core/backends/lium/test_api_client.py index 0e7b68803..6625123e2 100644 --- a/src/tests/_internal/core/backends/lium/test_api_client.py +++ b/src/tests/_internal/core/backends/lium/test_api_client.py @@ -1,33 +1,33 @@ +import httpx2 import pytest -import requests from dstack._internal.core.backends.lium.api_client import API_URL, LiumAPIClient, LiumAPIError class TestLiumAPIClient: - def test_identity_uses_api_key_and_timeout(self, requests_mock): - requests_mock.get(f"{API_URL}/users/me", json={"id": "user-id"}) + def test_identity_uses_api_key_and_timeout(self, http_mock): + http_mock.get(f"{API_URL}/users/me", json={"id": "user-id"}) assert LiumAPIClient("test-key").get_user() == {"id": "user-id"} - assert requests_mock.last_request.headers["X-API-Key"] == "test-key" - assert requests_mock.last_request.timeout == 30 + assert http_mock.last_request.headers["X-API-Key"] == "test-key" + assert http_mock.last_request.timeout["read"] == 30 - def test_version_reports_provider_features(self, requests_mock): + def test_version_reports_provider_features(self, http_mock): version = {"features": ["rent_idempotency"]} - requests_mock.get(f"{API_URL}/version", json=version) + http_mock.get(f"{API_URL}/version", json=version) assert LiumAPIClient("test-key").get_version() == version - def test_rental_sends_payload_and_idempotency_key(self, requests_mock): - requests_mock.post(f"{API_URL}/executors/node-id/rent", json={"pod_id": "pod-id"}) + def test_rental_sends_payload_and_idempotency_key(self, http_mock): + http_mock.post(f"{API_URL}/executors/node-id/rent", json={"pod_id": "pod-id"}) client = LiumAPIClient("test-key") payload = {"pod_name": "dstack-job", "template_id": "template-id", "gpu_count": 2} assert client.rent_executor("node-id", payload, "rent-key") == {"pod_id": "pod-id"} - assert requests_mock.last_request.json() == payload - assert requests_mock.last_request.headers["Idempotency-Key"] == "rent-key" + assert http_mock.last_request.json() == payload + assert http_mock.last_request.headers["Idempotency-Key"] == "rent-key" @pytest.mark.parametrize( ["method", "path", "payload"], @@ -40,19 +40,17 @@ def test_rental_sends_payload_and_idempotency_key(self, requests_mock): ), ], ) - def test_create_posts_payload_once(self, requests_mock, method, path, payload): - requests_mock.post(API_URL + path, json={"id": "resource-id"}) + def test_create_posts_payload_once(self, http_mock, method, path, payload): + http_mock.post(API_URL + path, json={"id": "resource-id"}) assert getattr(LiumAPIClient("test-key"), method)(payload) == {"id": "resource-id"} - assert requests_mock.last_request.json() == payload - assert requests_mock.call_count == 1 + assert http_mock.last_request.json() == payload + assert http_mock.call_count == 1 - @pytest.mark.parametrize("error", [requests.ReadTimeout, requests.ConnectionError]) - def test_rental_transport_error_does_not_retry_or_expose_credentials( - self, requests_mock, error - ): - requests_mock.post(f"{API_URL}/executors/node-id/rent", exc=error("secret")) + @pytest.mark.parametrize("error", [httpx2.ReadTimeout, httpx2.ConnectError]) + def test_rental_transport_error_does_not_retry_or_expose_credentials(self, http_mock, error): + http_mock.post(f"{API_URL}/executors/node-id/rent", exc=error("secret")) with pytest.raises(LiumAPIError) as exc: LiumAPIClient("secret").rent_executor("node-id", {"pod_name": "job"}, "rent-key") @@ -60,11 +58,11 @@ def test_rental_transport_error_does_not_retry_or_expose_credentials( assert exc.value.status_code is None assert "secret" not in str(exc.value) assert exc.value.__suppress_context__ - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 @pytest.mark.parametrize("status", [401, 403, 409, 429, 503]) - def test_http_error_preserves_status_and_code_without_body(self, requests_mock, status): - requests_mock.post( + def test_http_error_preserves_status_and_code_without_body(self, http_mock, status): + http_mock.post( f"{API_URL}/executors/node-id/rent", status_code=status, json={"error": {"code": "idempotency_outcome_unknown", "message": "secret"}}, @@ -76,13 +74,13 @@ def test_http_error_preserves_status_and_code_without_body(self, requests_mock, assert str(exc.value) == (f"Lium API returned HTTP {status} (idempotency_outcome_unknown)") assert exc.value.status_code == status assert exc.value.code == "idempotency_outcome_unknown" - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 @pytest.mark.parametrize( "code", ["node_unavailable\nsecret", "x" * 65, {"detail": "secret"}, "lium_api_secret"] ) - def test_error_omits_malformed_codes_and_reflected_api_key(self, requests_mock, code): - requests_mock.get( + def test_error_omits_malformed_codes_and_reflected_api_key(self, http_mock, code): + http_mock.get( f"{API_URL}/users/me", status_code=403, json={"error": {"code": code, "message": "private credentials"}}, @@ -94,10 +92,10 @@ def test_error_omits_malformed_codes_and_reflected_api_key(self, requests_mock, assert str(exc.value) == "Lium API returned HTTP 403" assert exc.value.code is None - def test_get_pod_returns_none_only_for_missing_pod(self, requests_mock): - requests_mock.get(f"{API_URL}/pods/pod-id", json={"id": "pod-id", "status": "PENDING"}) - requests_mock.get(f"{API_URL}/pods/missing", status_code=404) - requests_mock.get(f"{API_URL}/pods/forbidden", status_code=403) + def test_get_pod_returns_none_only_for_missing_pod(self, http_mock): + http_mock.get(f"{API_URL}/pods/pod-id", json={"id": "pod-id", "status": "PENDING"}) + http_mock.get(f"{API_URL}/pods/missing", status_code=404) + http_mock.get(f"{API_URL}/pods/forbidden", status_code=403) client = LiumAPIClient("test-key") assert client.get_pod("pod-id") == {"id": "pod-id", "status": "PENDING"} @@ -108,7 +106,7 @@ def test_get_pod_returns_none_only_for_missing_pod(self, requests_mock): @pytest.mark.parametrize("since", [None, "2026-10-16T08:00:00Z"]) def test_account_events_include_deleted_pods_and_request_maximum_history( - self, requests_mock, since + self, http_mock, since ): event = { "pod_id": "pod-id", @@ -116,14 +114,14 @@ def test_account_events_include_deleted_pods_and_request_maximum_history( "event_type": "pod-lifecycle", "to_status": "DELETED", } - requests_mock.get(f"{API_URL}/users/me/events", json=[event]) + http_mock.get(f"{API_URL}/users/me/events", json=[event]) assert LiumAPIClient("test-key").get_account_events(since) == [event] params = {"limit": ["1000"]} if since is not None: - params["since"] = [since.lower()] - assert requests_mock.last_request.qs == params + params["since"] = [since] + assert http_mock.last_request.qs == params @pytest.mark.parametrize( ["headers", "expected"], @@ -133,8 +131,8 @@ def test_account_events_include_deleted_pods_and_request_maximum_history( ({"Idempotent-Replayed": "true"}, True), ], ) - def test_refusal_exposes_idempotent_replay_header(self, requests_mock, headers, expected): - requests_mock.post( + def test_refusal_exposes_idempotent_replay_header(self, http_mock, headers, expected): + http_mock.post( f"{API_URL}/executors/node-id/rent", status_code=400, headers=headers, @@ -145,14 +143,14 @@ def test_refusal_exposes_idempotent_replay_header(self, requests_mock, headers, LiumAPIClient("test-key").rent_executor("node-id", {"pod_name": "job"}, "rent-key") assert exc.value.idempotent_replayed is expected - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 - def test_volume_create_and_lookup(self, requests_mock): + def test_volume_create_and_lookup(self, http_mock): volume = {"id": "volume-id", "name": "checkpoints"} - requests_mock.post(f"{API_URL}/volumes", json=volume) - requests_mock.get(f"{API_URL}/volumes/volume-id", json=volume) - requests_mock.get(f"{API_URL}/volumes/missing", status_code=404) - requests_mock.get( + http_mock.post(f"{API_URL}/volumes", json=volume) + http_mock.get(f"{API_URL}/volumes/volume-id", json=volume) + http_mock.get(f"{API_URL}/volumes/missing", status_code=404) + http_mock.get( f"{API_URL}/volumes/forbidden", status_code=403, json={"success": False, "message": "secret"}, @@ -160,7 +158,7 @@ def test_volume_create_and_lookup(self, requests_mock): client = LiumAPIClient("test-key") assert client.create_volume("checkpoints") == volume - assert requests_mock.last_request.json() == {"name": "checkpoints"} + assert http_mock.last_request.json() == {"name": "checkpoints"} assert client.get_volume("volume-id") == volume assert client.get_volume("missing") is None with pytest.raises(LiumAPIError) as exc: @@ -176,10 +174,8 @@ def test_volume_create_and_lookup(self, requests_mock): ("get_templates", "/templates"), ], ) - def test_lists_require_object_items(self, requests_mock, method, path): - requests_mock.get( - API_URL + path, [{"json": [{"id": "resource-id"}]}, {"json": ["invalid"]}] - ) + def test_lists_require_object_items(self, http_mock, method, path): + http_mock.get(API_URL + path, [{"json": [{"id": "resource-id"}]}, {"json": ["invalid"]}]) call = getattr(LiumAPIClient("test-key"), method) assert call() == [{"id": "resource-id"}] @@ -195,15 +191,15 @@ def test_lists_require_object_items(self, requests_mock, method, path): ("delete_volume", "/volumes/resource-id", 404), ], ) - def test_delete_is_idempotent(self, requests_mock, method, path, status): - requests_mock.delete(API_URL + path, status_code=status) + def test_delete_is_idempotent(self, http_mock, method, path, status): + http_mock.delete(API_URL + path, status_code=status) getattr(LiumAPIClient("test-key"), method)("resource-id") - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 - def test_delete_error_is_not_silenced(self, requests_mock): - requests_mock.delete(f"{API_URL}/pods/pod-id", status_code=503, text="secret") + def test_delete_error_is_not_silenced(self, http_mock): + http_mock.delete(f"{API_URL}/pods/pod-id", status_code=503, text="secret") with pytest.raises(LiumAPIError) as exc: LiumAPIClient("test-key").delete_pod("pod-id") @@ -211,8 +207,8 @@ def test_delete_error_is_not_silenced(self, requests_mock): assert exc.value.status_code == 503 assert str(exc.value) == "Lium API returned HTTP 503" - def test_redirect_does_not_forward_api_key(self, requests_mock): - requests_mock.get( + def test_redirect_does_not_forward_api_key(self, http_mock): + http_mock.get( f"{API_URL}/users/me", status_code=302, headers={"Location": "https://untrusted.example/identity"}, @@ -222,13 +218,13 @@ def test_redirect_does_not_forward_api_key(self, requests_mock): LiumAPIClient("test-key").get_user() assert exc.value.status_code == 302 - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 @pytest.mark.parametrize("body", ["not JSON", "null"]) - def test_invalid_create_response_does_not_retry(self, requests_mock, body): - requests_mock.post(f"{API_URL}/templates", text=body) + def test_invalid_create_response_does_not_retry(self, http_mock, body): + http_mock.post(f"{API_URL}/templates", text=body) with pytest.raises(LiumAPIError): LiumAPIClient("test-key").create_template({"docker_image": "ubuntu:24.04"}) - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 diff --git a/src/tests/_internal/core/backends/lium/test_configurator.py b/src/tests/_internal/core/backends/lium/test_configurator.py index a61be50f8..19fccd7ac 100644 --- a/src/tests/_internal/core/backends/lium/test_configurator.py +++ b/src/tests/_internal/core/backends/lium/test_configurator.py @@ -20,8 +20,8 @@ def test_validate_config(self): client.assert_called_once_with("test-key") client.return_value.get_user.assert_called_once_with() - def test_invalid_credentials(self, requests_mock): - requests_mock.get(f"{API_URL}/users/me", status_code=401) + def test_invalid_credentials(self, http_mock): + http_mock.get(f"{API_URL}/users/me", status_code=401) config = LiumBackendConfigWithCreds(creds=LiumCreds(api_key="invalid")) with pytest.raises(BackendInvalidCredentialsError) as exc: @@ -29,8 +29,8 @@ def test_invalid_credentials(self, requests_mock): assert exc.value.fields == [["creds", "api_key"]] - def test_server_error_is_not_invalid_credentials(self, requests_mock): - requests_mock.get(f"{API_URL}/users/me", status_code=503) + def test_server_error_is_not_invalid_credentials(self, http_mock): + http_mock.get(f"{API_URL}/users/me", status_code=503) config = LiumBackendConfigWithCreds(creds=LiumCreds(api_key="test-key")) with pytest.raises(LiumAPIError): diff --git a/src/tests/_internal/core/backends/massedcompute/test_api_client.py b/src/tests/_internal/core/backends/massedcompute/test_api_client.py index 46863e497..301b516b5 100644 --- a/src/tests/_internal/core/backends/massedcompute/test_api_client.py +++ b/src/tests/_internal/core/backends/massedcompute/test_api_client.py @@ -1,7 +1,7 @@ import traceback +import httpx2 import pytest -import requests from dstack._internal.core.backends.massedcompute.api_client import API_URL, MassedComputeAPIClient from dstack._internal.core.errors import ComputeError @@ -9,15 +9,15 @@ class TestLaunch: @pytest.mark.parametrize("visible", [True, False]) - def test_lost_response(self, requests_mock, visible): + def test_lost_response(self, http_mock, visible): name = "dstack-main-gpu-abcdefgh12345678" vm_id = "465e97cc-77cc-47dd-bb7c-1835ee127f9f" other = {"name": "other", "uuid": "other-id", "status": "Running"} instances = [other] if visible: instances.append({"name": name, "uuid": vm_id, "status": "Initializing"}) - launch = requests_mock.post(f"{API_URL}/instance/launch", exc=requests.ReadTimeout) - requests_mock.get(f"{API_URL}/instance", json={"runningInstances": instances}) + http_mock.post(f"{API_URL}/instance/launch", exc=httpx2.ReadTimeout) + http_mock.get(f"{API_URL}/instance", json={"runningInstances": instances}) client = MassedComputeAPIClient("test-key") if visible: @@ -25,12 +25,12 @@ def test_lost_response(self, requests_mock, visible): else: with pytest.raises(ComputeError, match="ReadTimeout"): client.launch(name, "gpu_1x_pro_6000_blackwell", "true") - assert launch.call_count == 1 + assert [r.method for r in http_mock.request_history].count("POST") == 1 class TestGetInstance: - def test_invalid_response_keeps_password_out_of_traceback(self, requests_mock): - requests_mock.get( + def test_invalid_response_keeps_password_out_of_traceback(self, http_mock): + http_mock.get( f"{API_URL}/instance/vm-id", json={"runningInstances": [{"uuid": "vm-id", "password": "vm-login-secret"}]}, ) diff --git a/src/tests/_internal/core/backends/massedcompute/test_compute.py b/src/tests/_internal/core/backends/massedcompute/test_compute.py index e1d7fc2eb..ed6ce43a4 100644 --- a/src/tests/_internal/core/backends/massedcompute/test_compute.py +++ b/src/tests/_internal/core/backends/massedcompute/test_compute.py @@ -13,19 +13,19 @@ class TestTerminateInstance: - def test_waits_for_disappearance_and_accepts_repeated_calls(self, requests_mock): + def test_waits_for_disappearance_and_accepts_repeated_calls(self, http_mock): compute = MassedComputeCompute( MassedComputeConfig(creds=MassedComputeCreds(api_key="test")) ) vm = {"uuid": "vm-id", "name": "vm", "status": "Stopped"} - requests_mock.get( + http_mock.get( f"{API_URL}/instance/vm-id", [ {"json": {"runningInstances": [vm]}}, {"json": {"runningInstances": []}}, ], ) - terminate = requests_mock.post(f"{API_URL}/instance/terminate", status_code=202) + http_mock.post(f"{API_URL}/instance/terminate", status_code=202) # A stopped VM on MassedCompute is still billable. with pytest.raises(NotYetTerminated): @@ -33,12 +33,12 @@ def test_waits_for_disappearance_and_accepts_repeated_calls(self, requests_mock) compute.terminate_instance("vm-id", "any") compute.terminate_instance("vm-id", "any") - assert terminate.call_count == 1 - assert terminate.last_request.json() == {"instanceUuids": ["vm-id"]} + (terminate,) = [r for r in http_mock.request_history if r.method == "POST"] + assert terminate.json() == {"instanceUuids": ["vm-id"]} class TestListResourceGroups: - def test_lists_only_instances_with_a_provider_ref(self, requests_mock): + def test_lists_only_instances_with_a_provider_ref(self, http_mock): compute = MassedComputeCompute( MassedComputeConfig(creds=MassedComputeCreds(api_key="test")) ) @@ -48,7 +48,7 @@ def test_lists_only_instances_with_a_provider_ref(self, requests_mock): "status": "Running", "created": "2026-11-25T14:48:48.000Z", } - requests_mock.get( + http_mock.get( f"{API_URL}/instance", json={"runningInstances": [vm, {**vm, "name": "manual", "uuid": "another-vm"}]}, ) diff --git a/src/tests/_internal/core/backends/runpod/test_api_client.py b/src/tests/_internal/core/backends/runpod/test_api_client.py index d2bf7cba5..9152025b2 100644 --- a/src/tests/_internal/core/backends/runpod/test_api_client.py +++ b/src/tests/_internal/core/backends/runpod/test_api_client.py @@ -21,8 +21,8 @@ def _error(status: int, detail: str, errors: list[str] | None = None) -> dict: class TestRunpodApiClientCreatePod: - def test_gpu_pod(self, requests_mock): - requests_mock.post(f"{API_V2_URL}/pods", status_code=201, json={"id": "pod-1"}) + def test_gpu_pod(self, http_mock): + http_mock.post(f"{API_V2_URL}/pods", status_code=201, json={"id": "pod-1"}) pod = _client().create_pod( name="test-pod", @@ -44,8 +44,8 @@ def test_gpu_pod(self, requests_mock): ) assert pod["id"] == "pod-1" - assert requests_mock.last_request.headers["Authorization"] == "Bearer test" - assert requests_mock.last_request.json() == { + assert http_mock.last_request.headers["Authorization"] == "Bearer test" + assert http_mock.last_request.json() == { "name": "test-pod", "cloud": "SECURE", "dataCenterIds": ["EU-RO-1"], @@ -66,8 +66,8 @@ def test_gpu_pod(self, requests_mock): "env": {"RUNPOD_POD_USER": "0"}, } - def test_cpu_pod(self, requests_mock): - requests_mock.post(f"{API_V2_URL}/pods", status_code=201, json={"id": "pod-1"}) + def test_cpu_pod(self, http_mock): + http_mock.post(f"{API_V2_URL}/pods", status_code=201, json={"id": "pod-1"}) _client().create_pod( name="test-pod", @@ -80,7 +80,7 @@ def test_cpu_pod(self, requests_mock): cmd=["-c", "echo hi"], ) - assert requests_mock.last_request.json() == { + assert http_mock.last_request.json() == { "name": "test-pod", "cloud": "SECURE", "cpu": {"id": "cpu3c", "vcpuCount": 4}, @@ -105,8 +105,8 @@ def test_rejects_both_gpu_and_cpu(self): class TestRunpodApiClientErrors: - def test_v2_error_response(self, requests_mock): - requests_mock.post( + def test_v2_error_response(self, http_mock): + http_mock.post( f"{API_V2_URL}/registries", status_code=422, json=_error(422, "Request validation failed.", ["$: missing property 'name'"]), @@ -123,8 +123,8 @@ def test_v2_error_response(self, requests_mock): ) @pytest.mark.parametrize("status_code", [401, 403]) - def test_auth_error_response(self, requests_mock, status_code: int): - requests_mock.get( + def test_auth_error_response(self, http_mock, status_code: int): + http_mock.get( f"{API_V2_URL}/account/ssh-keys", status_code=status_code, json=_error(status_code, "Invalid token"), @@ -132,22 +132,20 @@ def test_auth_error_response(self, requests_mock, status_code: int): assert _client().validate_api_key() is False - def test_non_json_auth_error_response(self, requests_mock): - requests_mock.get( + def test_non_json_auth_error_response(self, http_mock): + http_mock.get( f"{API_V2_URL}/pods/pod-1", status_code=403, - reason="Forbidden", text="Access denied", ) with pytest.raises(BackendInvalidCredentialsError, match="Forbidden: "): _client().get_pod("pod-1") - def test_non_json_error_response(self, requests_mock): - requests_mock.get( + def test_non_json_error_response(self, http_mock): + http_mock.get( f"{API_V2_URL}/pods/pod-1", status_code=429, - reason="Too Many Requests", text="\n" + "x" * 1000 + "\n", ) @@ -161,25 +159,25 @@ def test_non_json_error_response(self, requests_mock): class TestRunpodApiClientNotFound: - def test_get_pod(self, requests_mock): - requests_mock.get(f"{API_V2_URL}/pods/pod-1", status_code=404, json=_error(404, "-")) + def test_get_pod(self, http_mock): + http_mock.get(f"{API_V2_URL}/pods/pod-1", status_code=404, json=_error(404, "-")) assert _client().get_pod("pod-1") is None - def test_terminate_pod(self, requests_mock): - requests_mock.delete(f"{API_V2_URL}/pods/pod-1", status_code=404, json=_error(404, "-")) + def test_terminate_pod(self, http_mock): + http_mock.delete(f"{API_V2_URL}/pods/pod-1", status_code=404, json=_error(404, "-")) assert _client().terminate_pod("pod-1") is False - def test_delete_network_volume(self, requests_mock): - requests_mock.delete( + def test_delete_network_volume(self, http_mock): + http_mock.delete( f"{API_V2_URL}/network-volumes/vol-1", status_code=404, json=_error(404, "-") ) assert _client().delete_network_volume("vol-1") is False - def test_other_errors_are_raised(self, requests_mock): - requests_mock.delete( + def test_other_errors_are_raised(self, http_mock): + http_mock.delete( f"{API_V2_URL}/pods/pod-1", status_code=409, json=_error(409, "Pod belongs to a cluster"), @@ -196,8 +194,8 @@ def _page(self, pod_ids: list[str], next_cursor: str | None) -> dict: "pagination": {"nextCursor": next_cursor, "hasNextPage": next_cursor is not None}, } - def test_follows_cursor(self, requests_mock): - requests_mock.get( + def test_follows_cursor(self, http_mock): + http_mock.get( f"{API_V2_URL}/pods", [ {"json": self._page(["pod-1", "pod-2"], "cursor-1")}, @@ -208,15 +206,15 @@ def test_follows_cursor(self, requests_mock): pods = _client().list_pods() assert [pod["id"] for pod in pods] == ["pod-1", "pod-2", "pod-3"] - assert [r.qs for r in requests_mock.request_history] == [ + assert [r.qs for r in http_mock.request_history] == [ {"limit": ["1000"]}, {"limit": ["1000"], "cursor": ["cursor-1"]}, ] - def test_stops_at_max_pages(self, requests_mock): - requests_mock.get(f"{API_V2_URL}/pods", json=self._page(["pod-1"], "cursor-1")) + def test_stops_at_max_pages(self, http_mock): + http_mock.get(f"{API_V2_URL}/pods", json=self._page(["pod-1"], "cursor-1")) pods = _client().list_pods() assert len(pods) == PAGINATION_MAX_PAGES - assert requests_mock.call_count == PAGINATION_MAX_PAGES + assert http_mock.call_count == PAGINATION_MAX_PAGES diff --git a/src/tests/_internal/core/backends/seeweb/test_api_client.py b/src/tests/_internal/core/backends/seeweb/test_api_client.py index 4ada113dc..e054641d4 100644 --- a/src/tests/_internal/core/backends/seeweb/test_api_client.py +++ b/src/tests/_internal/core/backends/seeweb/test_api_client.py @@ -1,5 +1,5 @@ +import httpx2 import pytest -import requests from dstack._internal.core.backends.seeweb.api_client import API_URL, SeewebApiClient from dstack._internal.core.errors import ( @@ -9,35 +9,35 @@ ) -def test_validate_api_key_and_auth_header(requests_mock): - requests_mock.get(f"{API_URL}/regions", json={"status": "ok", "regions": []}) +def test_validate_api_key_and_auth_header(http_mock): + http_mock.get(f"{API_URL}/regions", json={"status": "ok", "regions": []}) assert SeewebApiClient("token").validate_api_key() is True - assert requests_mock.last_request.headers["X-APITOKEN"] == "token" + assert http_mock.last_request.headers["X-APITOKEN"] == "token" -def test_validate_api_key_returns_false_for_unauthorized(requests_mock): - requests_mock.get(f"{API_URL}/regions", status_code=401, json={"message": "unauthorized"}) +def test_validate_api_key_returns_false_for_unauthorized(http_mock): + http_mock.get(f"{API_URL}/regions", status_code=401, json={"message": "unauthorized"}) assert SeewebApiClient("bad").validate_api_key() is False -def test_request_wraps_network_errors(requests_mock): - requests_mock.get(f"{API_URL}/regions", exc=requests.ConnectTimeout("timed out")) +def test_request_wraps_network_errors(http_mock): + http_mock.get(f"{API_URL}/regions", exc=httpx2.ConnectTimeout("timed out")) with pytest.raises(BackendError, match="Seeweb API request failed"): SeewebApiClient("token").validate_api_key() -def test_forbidden_raises_invalid_credentials(requests_mock): - requests_mock.get(f"{API_URL}/servers/server", status_code=403, text="forbidden") +def test_forbidden_raises_invalid_credentials(http_mock): + http_mock.get(f"{API_URL}/servers/server", status_code=403, text="forbidden") with pytest.raises(BackendInvalidCredentialsError): SeewebApiClient("bad").get_server("server") -def test_get_available_plans_parses_regions_and_active_images(requests_mock): - requests_mock.get( +def test_get_available_plans_parses_regions_and_active_images(http_mock): + http_mock.get( f"{API_URL}/plans/availables", json={ "status": "ok", @@ -73,8 +73,8 @@ def test_get_available_plans_parses_regions_and_active_images(requests_mock): } -def test_get_or_create_ssh_key_reuses_key_ignoring_comment(requests_mock): - requests_mock.get( +def test_get_or_create_ssh_key_reuses_key_ignoring_comment(http_mock): + http_mock.get( f"{API_URL}/sshkeys", json={ "status": "ok", @@ -90,29 +90,29 @@ def test_get_or_create_ssh_key_reuses_key_ignoring_comment(requests_mock): label = SeewebApiClient("token").get_or_create_ssh_key("ssh-ed25519 AAAATEST new-comment") assert label == "existing" - assert requests_mock.call_count == 1 + assert http_mock.call_count == 1 -def test_get_or_create_ssh_key_creates_missing_key(requests_mock): - requests_mock.get(f"{API_URL}/sshkeys", json={"status": "ok", "pubkeys": []}) - requests_mock.post(f"{API_URL}/sshkeys", json={"status": "ok"}) +def test_get_or_create_ssh_key_creates_missing_key(http_mock): + http_mock.get(f"{API_URL}/sshkeys", json={"status": "ok", "pubkeys": []}) + http_mock.post(f"{API_URL}/sshkeys", json={"status": "ok"}) public_key = "ssh-ed25519 AAAATEST comment with spaces" label = SeewebApiClient("token").get_or_create_ssh_key(public_key) assert label.startswith("dstack-") - assert requests_mock.last_request.json() == {"key": public_key, "label": label} + assert http_mock.last_request.json() == {"key": public_key, "label": label} -def test_get_or_create_ssh_key_rejects_invalid_key(requests_mock): +def test_get_or_create_ssh_key_rejects_invalid_key(http_mock): with pytest.raises(ValueError, match="Invalid SSH public key"): SeewebApiClient("token").get_or_create_ssh_key('invalid "key"') - assert requests_mock.call_count == 0 + assert http_mock.call_count == 0 -def test_create_server_parses_action_id(requests_mock): - requests_mock.post( +def test_create_server_parses_action_id(http_mock): + http_mock.post( f"{API_URL}/servers", json={ "status": "ok", @@ -134,8 +134,8 @@ def test_create_server_parses_action_id(requests_mock): @pytest.mark.parametrize("status_code", [200, 400]) -def test_create_server_maps_capacity_errors(requests_mock, status_code): - requests_mock.post( +def test_create_server_maps_capacity_errors(http_mock, status_code): + http_mock.post( f"{API_URL}/servers", status_code=status_code, json={"status": "error", "message": "Plan is not available in this region"}, @@ -145,8 +145,8 @@ def test_create_server_maps_capacity_errors(requests_mock, status_code): SeewebApiClient("token").create_server({}) -def test_create_server_maps_other_errors(requests_mock): - requests_mock.post( +def test_create_server_maps_other_errors(http_mock): + http_mock.post( f"{API_URL}/servers", status_code=500, json={"status": "error", "message": "internal failure"}, @@ -156,12 +156,12 @@ def test_create_server_maps_other_errors(requests_mock): SeewebApiClient("token").create_server({}) -def test_get_action_and_server(requests_mock): - requests_mock.get( +def test_get_action_and_server(http_mock): + http_mock.get( f"{API_URL}/actions/35", json={"status": "ok", "action": {"id": 35, "status": "completed"}}, ) - requests_mock.get( + http_mock.get( f"{API_URL}/servers/ec-test", json={"status": "ok", "server": {"name": "ec-test", "ipv4": "192.0.2.1"}}, ) @@ -175,8 +175,8 @@ def test_get_action_and_server(requests_mock): assert server["ipv4"] == "192.0.2.1" -def test_delete_server_is_idempotent(requests_mock): - requests_mock.delete( +def test_delete_server_is_idempotent(http_mock): + http_mock.delete( f"{API_URL}/servers/missing", status_code=404, json={"status": "error", "message": "not found"}, From a469058d2249bdde3358b63b74ea4e8403436047 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:19:18 +0500 Subject: [PATCH 05/37] Move REST plugin and tokenizer config requests to httpx2 --- .../server/services/services/options.py | 15 ++++---- .../plugins/builtin/rest_plugin/_plugin.py | 19 +++++----- .../builtin/rest_plugin/test_plugin.py | 37 ++++++++----------- 3 files changed, 34 insertions(+), 37 deletions(-) diff --git a/src/dstack/_internal/server/services/services/options.py b/src/dstack/_internal/server/services/services/options.py index 40b45e797..dd8ffd27d 100644 --- a/src/dstack/_internal/server/services/services/options.py +++ b/src/dstack/_internal/server/services/services/options.py @@ -1,10 +1,11 @@ from typing import Dict, Optional -import requests +import httpx2 from dstack._internal.core.errors import ServerClientError from dstack._internal.core.models.configurations import ServiceConfiguration from dstack._internal.core.models.services import AnyModel +from dstack._internal.utils.http import HTTPClient def complete_service_model(model_info: AnyModel, env: Dict[str, str]): @@ -27,11 +28,11 @@ def get_tokenizer_config(model_id: str, hf_token: Optional[str] = None) -> dict: if hf_token is not None: headers["Authorization"] = f"Bearer {hf_token}" try: - resp = requests.get( - f"https://huggingface.co/{model_id}/resolve/main/tokenizer_config.json", - timeout=10, - headers=headers, - ) + with HTTPClient(timeout=10, follow_redirects=True) as client: + resp = client.get( + f"https://huggingface.co/{model_id}/resolve/main/tokenizer_config.json", + headers=headers, + ) if resp.status_code == 403: raise ServerClientError("Private HF models are not supported") if resp.status_code == 401: @@ -40,7 +41,7 @@ def get_tokenizer_config(model_id: str, hf_token: Optional[str] = None) -> dict: message = "Failed to access gated model. Invalid HF_TOKEN env." raise ServerClientError(message) resp.raise_for_status() - except requests.RequestException as e: + except httpx2.HTTPError as e: raise ServerClientError(f"Failed to get tokenizer info: {e}") return resp.json() diff --git a/src/dstack/plugins/builtin/rest_plugin/_plugin.py b/src/dstack/plugins/builtin/rest_plugin/_plugin.py index a4d796fd1..e0353f89b 100644 --- a/src/dstack/plugins/builtin/rest_plugin/_plugin.py +++ b/src/dstack/plugins/builtin/rest_plugin/_plugin.py @@ -2,7 +2,7 @@ import os from typing import Dict, Optional, Type -import requests +import httpx2 from pydantic import ValidationError from dstack._internal.core.compatibility.fleets import get_fleet_spec_excludes @@ -13,6 +13,7 @@ from dstack._internal.core.models.fleets import FleetSpec from dstack._internal.core.models.gateways import GatewaySpec from dstack._internal.core.models.volumes import VolumeSpec +from dstack._internal.utils.http import HTTPClient from dstack.plugins import ApplyPolicy, ApplySpec, Plugin, RunSpec, get_plugin_logger from dstack.plugins.builtin.rest_plugin import ( FleetSpecRequest, @@ -59,23 +60,23 @@ def _call_plugin_service( # mapping, or a bool), so omit the key entirely when there is nothing to exclude. exclude = {"spec": excludes} if excludes is not None else None try: - response = requests.post( - f"{self._plugin_service_uri}{endpoint}", - json=spec_request.model_dump(exclude=exclude), - headers={"accept": "application/json", "Content-Type": "application/json"}, - timeout=PLUGIN_REQUEST_TIMEOUT_SEC, - ) + with HTTPClient(timeout=PLUGIN_REQUEST_TIMEOUT_SEC, follow_redirects=True) as client: + response = client.post( + f"{self._plugin_service_uri}{endpoint}", + json=spec_request.model_dump(exclude=exclude), + headers={"accept": "application/json", "Content-Type": "application/json"}, + ) response.raise_for_status() spec_json = json.loads(response.text) return spec_json - except requests.exceptions.ConnectionError as e: + except (httpx2.ConnectError, httpx2.ConnectTimeout) as e: logger.error( f"Could not connect to plugin service at {self._plugin_service_uri}: %s", e ) raise ServerClientError( f"Could not connect to plugin service at {self._plugin_service_uri}" ) - except requests.RequestException as e: + except httpx2.HTTPError as e: logger.error("Request to the plugin service failed: %s", e) raise ServerClientError("Request to the plugin service failed") diff --git a/src/tests/plugins/builtin/rest_plugin/test_plugin.py b/src/tests/plugins/builtin/rest_plugin/test_plugin.py index 2876d5ee5..057d10137 100644 --- a/src/tests/plugins/builtin/rest_plugin/test_plugin.py +++ b/src/tests/plugins/builtin/rest_plugin/test_plugin.py @@ -1,11 +1,10 @@ import json import os from contextlib import nullcontext as does_not_raise -from unittest.mock import Mock +import httpx2 import pytest import pytest_asyncio -import requests from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.core.errors import ServerClientError, ServerError @@ -104,11 +103,10 @@ async def test_on_run_apply_plugin_service_uri_not_set(self): "spec", ["run_spec", "fleet_spec", "volume_spec", "gateway_spec"], indirect=True ) async def test_on_apply_plugin_service_returns_mutated_spec( - self, mocker, test_db, user, project, spec + self, mocker, http_mock, test_db, user, project, spec ): mocker.patch.dict(os.environ, {PLUGIN_SERVICE_URI_ENV_VAR_NAME: "http://mock"}) policy = CustomApplyPolicy() - mock_response = Mock() response_dict = {"spec": spec.model_dump(), "error": None} has_profile = isinstance(spec, (RunSpec, FleetSpec)) @@ -117,9 +115,8 @@ async def test_on_apply_plugin_service_returns_mutated_spec( else: response_dict["spec"]["configuration_path"] = "/path/to/something" - mock_response.text = json.dumps(response_dict) - mock_response.raise_for_status = Mock() - mocker.patch("requests.post", return_value=mock_response) + response_text = json.dumps(response_dict) + http_mock.post("http://mock", text=response_text) result = policy.on_apply(user=user.name, project=project.name, spec=spec) assert result == type(spec)(**response_dict["spec"]) @@ -128,10 +125,12 @@ async def test_on_apply_plugin_service_returns_mutated_spec( @pytest.mark.parametrize( "spec", ["run_spec", "fleet_spec", "volume_spec", "gateway_spec"], indirect=True ) - async def test_on_apply_plugin_service_call_fails(self, mocker, test_db, user, project, spec): + async def test_on_apply_plugin_service_call_fails( + self, mocker, http_mock, test_db, user, project, spec + ): mocker.patch.dict(os.environ, {PLUGIN_SERVICE_URI_ENV_VAR_NAME: "http://mock"}) policy = CustomApplyPolicy() - mocker.patch("requests.post", side_effect=requests.RequestException("fail")) + http_mock.post("http://mock", exc=httpx2.ReadError("fail")) with pytest.raises(ServerClientError): policy.on_apply(user=user.name, project=project.name, spec=spec) @@ -141,11 +140,11 @@ async def test_on_apply_plugin_service_call_fails(self, mocker, test_db, user, p "spec", ["run_spec", "fleet_spec", "volume_spec", "gateway_spec"], indirect=True ) async def test_on_apply_plugin_service_connection_fails( - self, mocker, test_db, user, project, spec + self, mocker, http_mock, test_db, user, project, spec ): mocker.patch.dict(os.environ, {PLUGIN_SERVICE_URI_ENV_VAR_NAME: "http://mock"}) policy = CustomApplyPolicy() - mocker.patch("requests.post", side_effect=requests.ConnectionError("Failed to connect")) + http_mock.post("http://mock", exc=httpx2.ConnectError("Failed to connect")) with pytest.raises(ServerClientError): policy.on_apply(user=user.name, project=project.name, spec=spec) @@ -155,14 +154,12 @@ async def test_on_apply_plugin_service_connection_fails( "spec", ["run_spec", "fleet_spec", "volume_spec", "gateway_spec"], indirect=True ) async def test_on_apply_plugin_service_returns_invalid_spec( - self, mocker, test_db, user, project, spec + self, mocker, http_mock, test_db, user, project, spec ): mocker.patch.dict(os.environ, {PLUGIN_SERVICE_URI_ENV_VAR_NAME: "http://mock"}) policy = CustomApplyPolicy() - mock_response = Mock() - mock_response.text = json.dumps({"invalid-key": "abc"}) - mock_response.raise_for_status = Mock() - mocker.patch("requests.post", return_value=mock_response) + response_text = json.dumps({"invalid-key": "abc"}) + http_mock.post("http://mock", text=response_text) with pytest.raises(ServerClientError): policy.on_apply(user.name, project=project.name, spec=spec) @@ -192,15 +189,13 @@ async def test_on_apply_plugin_service_returns_invalid_spec( ], ) async def test_on_apply_plugin_service_error_handling( - self, mocker, test_db, user, project, spec, error, expectation + self, mocker, http_mock, test_db, user, project, spec, error, expectation ): mocker.patch.dict(os.environ, {PLUGIN_SERVICE_URI_ENV_VAR_NAME: "http://mock"}) policy = CustomApplyPolicy() - mock_response = Mock() response_dict = {"spec": spec.model_dump(), "error": error} - mock_response.text = json.dumps(response_dict) - mock_response.raise_for_status = Mock() - mocker.patch("requests.post", return_value=mock_response) + response_text = json.dumps(response_dict) + http_mock.post("http://mock", text=response_text) with expectation: result = policy.on_apply(user=user.name, project=project.name, spec=spec) assert result == type(spec)(**response_dict["spec"]) From f6ad0b9fea0db27714fdbf46e7303ee2e31c5bf0 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:19:56 +0500 Subject: [PATCH 06/37] Move Python API and CLI to httpx2 APIClient now times out (15s connect, 600s otherwise), follows redirects as before, and wraps all request errors in ClientError. http+unix:// server URLs keep working, so requests-unixsocket is no longer needed. --- pyproject.toml | 1 - src/dstack/_internal/cli/commands/project.py | 11 +- src/dstack/_internal/cli/utils/common.py | 14 +- src/dstack/_internal/cli/utils/updates.py | 18 +-- src/dstack/api/server/__init__.py | 67 +++++++-- src/dstack/api/server/_group.py | 5 +- src/dstack/api/server/_presets.py | 11 +- .../cli/services/presets/test_registry.py | 43 ++---- .../core/services/test_api_client.py | 2 +- src/tests/api/server/common.py | 11 +- src/tests/api/server/test_api_client.py | 142 ++++++++++++++---- 11 files changed, 218 insertions(+), 107 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 522c0321c..2dc21ff33 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,7 +13,6 @@ classifiers = [ dependencies = [ "pyyaml", "requests", - "requests-unixsocket>=0.4.1", "httpx2>=2.16.2", "certifi", "typing-extensions>=4.0.0", diff --git a/src/dstack/_internal/cli/commands/project.py b/src/dstack/_internal/cli/commands/project.py index 45a0ef6ef..e616cb75d 100644 --- a/src/dstack/_internal/cli/commands/project.py +++ b/src/dstack/_internal/cli/commands/project.py @@ -3,7 +3,6 @@ from typing import Optional import questionary -from requests import HTTPError from rich.table import Table import dstack.api.server @@ -138,15 +137,7 @@ def _command(self, args: argparse.Namespace): def _add(self, args: argparse.Namespace): config_manager = ConfigManager() api_client = dstack.api.server.APIClient(base_url=args.url, token=args.token) - try: - api_client.projects.get(args.name) - except HTTPError as e: - if e.response is not None and e.response.status_code == 403: - raise CLIError("Forbidden. Ensure the token is valid.") - elif e.response is not None and e.response.status_code == 404: - raise CLIError(f"Project '{args.name}' not found.") - else: - raise e + api_client.projects.get(args.name) default_project = config_manager.get_project_config() if ( default_project is None diff --git a/src/dstack/_internal/cli/utils/common.py b/src/dstack/_internal/cli/utils/common.py index 8f54978bc..b89c51706 100644 --- a/src/dstack/_internal/cli/utils/common.py +++ b/src/dstack/_internal/cli/utils/common.py @@ -5,7 +5,7 @@ from pathlib import Path from typing import Any, Optional -import requests +import httpx2 from rich.console import Console from rich.file_proxy import FileProxy from rich.prompt import Confirm @@ -18,6 +18,7 @@ from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.instances import InstanceAvailability from dstack._internal.utils.common import get_dstack_dir, parse_since +from dstack._internal.utils.http import HTTPClient _colors = { "secondary": "grey58", @@ -173,14 +174,11 @@ def resolve_url(url: str, timeout: float = 5.0) -> str: if not url.startswith("http://") and not url.startswith("https://"): url = "http://" + url try: - response = requests.get( - url, - allow_redirects=True, - timeout=timeout, - ) - except requests.exceptions.ConnectionError as e: + with HTTPClient(timeout=timeout, follow_redirects=True) as client: + response = client.get(url) + except (httpx2.ConnectError, httpx2.ConnectTimeout) as e: raise ValueError(f"Failed to resolve url {url}") from e - return response.url + return str(response.url) def format_entity_reference(name: str, project: str, current_project: str) -> str: diff --git a/src/dstack/_internal/cli/utils/updates.py b/src/dstack/_internal/cli/utils/updates.py index a84c88299..3130246d2 100644 --- a/src/dstack/_internal/cli/utils/updates.py +++ b/src/dstack/_internal/cli/utils/updates.py @@ -3,11 +3,11 @@ from pathlib import Path from typing import Optional -import requests from packaging import version as pkg_version from dstack import version from dstack._internal.cli.utils.common import error_console +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) @@ -29,14 +29,14 @@ def anonymous_installation_id() -> str: def get_latest_version() -> Optional[str]: latest_version_url = f"https://get.dstack.ai/{_get_channel()}/latest-version" try: - response = requests.get( - latest_version_url, - params={ - "anonymous_installation_id": anonymous_installation_id(), - "version": version.__version__, - }, - timeout=5, - ) + with HTTPClient(timeout=5, follow_redirects=True) as client: + response = client.get( + latest_version_url, + params={ + "anonymous_installation_id": anonymous_installation_id(), + "version": version.__version__, + }, + ) if response.status_code == 200: return response.text.strip() else: diff --git a/src/dstack/api/server/__init__.py b/src/dstack/api/server/__init__.py index d20d99cb6..02ce29751 100644 --- a/src/dstack/api/server/__init__.py +++ b/src/dstack/api/server/__init__.py @@ -1,11 +1,12 @@ import hashlib import os import pprint +import ssl import time -from typing import Dict, List, Optional, Type, Union +import urllib.parse +from typing import Dict, List, Optional, Tuple, Type, Union -import requests -import requests_unixsocket +import httpx2 from dstack import version from dstack._internal.core.errors import ( @@ -14,6 +15,7 @@ ServerClientError, URLNotFoundError, ) +from dstack._internal.utils.http import HTTPClient from dstack._internal.utils.logging import get_logger from dstack.api.server._auth import AuthAPIClient from dstack.api.server._backends import BackendsAPIClient @@ -36,6 +38,8 @@ _MAX_RETRIES = 3 _RETRY_INTERVAL = 1 +# Some requests take long, e.g. applying a plan. +_TIMEOUT = httpx2.Timeout(600, connect=15) class APIClient: @@ -66,16 +70,21 @@ def __init__(self, base_url: str, token: Optional[str] = None): token: The API token. """ self._base_url = base_url.rstrip("/") - self._s = requests.session() - if self._base_url.startswith("http+unix://"): - self._s.mount("http+unix://", requests_unixsocket.UnixAdapter()) + self._request_base_url, socket_path = _parse_base_url(self._base_url) + headers = {} self._token = None if token is not None: self._token = token - self._s.headers.update({"Authorization": f"Bearer {token}"}) + headers["Authorization"] = f"Bearer {token}" client_api_version = os.getenv("DSTACK_CLIENT_API_VERSION", version.__version__) if client_api_version is not None: - self._s.headers.update({"X-API-VERSION": client_api_version}) + headers["X-API-VERSION"] = client_api_version + self._client = HTTPClient( + headers=headers, + timeout=_TIMEOUT, + follow_redirects=True, + transport=httpx2.HTTPTransport(uds=socket_path) if socket_path is not None else None, + ) self._logger = get_logger(__name__) @property @@ -169,26 +178,42 @@ def _request( body: Optional[Union[str, bytes]] = None, raise_for_status: bool = True, method: str = "POST", + stream: bool = False, **kwargs, - ) -> requests.Response: + ) -> httpx2.Response: + """ + Raises only dstack errors. With `stream=True`, the caller reads the response body, + e.g. with `iter_bytes()`, and handles `httpx2.RequestError` while reading it. + """ path = path.lstrip("/") if body is not None: kwargs.setdefault("headers", {})["Content-Type"] = "application/json" - kwargs["data"] = body + kwargs["content"] = body - self._logger.debug("POST /%s", path) + self._logger.debug("%s /%s", method, path) + try: + request = self._client.build_request( + method, f"{self._request_base_url}/{path}", **kwargs + ) + except httpx2.InvalidURL as e: + raise ClientError(f"Invalid dstack server URL {self._base_url}: {e}") from e for _ in range(_MAX_RETRIES): try: - # TODO: set adequate timeout here or everywhere the method is used - resp = self._s.request(method, f"{self._base_url}/{path}", **kwargs) + resp = self._client.send(request, stream=stream) break - except requests.exceptions.ConnectionError as e: + except (httpx2.ConnectError, httpx2.ConnectTimeout) as e: self._logger.debug("Could not connect to server: %s", e) time.sleep(_RETRY_INTERVAL) + except (httpx2.RequestError, ssl.SSLError) as e: + raise ClientError(f"Failed to request {self._base_url}/{path}: {e!r}") from e else: raise ClientError(f"Failed to connect to dstack server {self._base_url}") if 400 <= resp.status_code < 600: + try: + resp.read() + except httpx2.RequestError as e: + raise ClientError(f"Failed to request {self._base_url}/{path}: {e!r}") from e self._logger.debug( "Error requesting %s. Status: %s. Headers: %s. Body: %s", resp.request.url, @@ -228,3 +253,17 @@ def _request( cls.code: cls for cls in ServerClientError.__subclasses__() } _server_client_errors[ServerClientError.code] = ServerClientError + + +def _parse_base_url(base_url: str) -> Tuple[str, Optional[str]]: + """ + Returns the URL to send requests to and, for `http+unix://[/]` + URLs, the Unix socket path. + """ + if not base_url.startswith("http+unix://"): + return base_url, None + quoted_socket_path, _, prefix = base_url[len("http+unix://") :].partition("/") + url = "http://localhost" + if prefix: + url += f"/{prefix}" + return url, urllib.parse.unquote(quoted_socket_path) diff --git a/src/dstack/api/server/_group.py b/src/dstack/api/server/_group.py index 7ed336fec..6515f1aa3 100644 --- a/src/dstack/api/server/_group.py +++ b/src/dstack/api/server/_group.py @@ -1,7 +1,7 @@ from logging import Logger from typing import Optional, Protocol, Union -import requests +import httpx2 class APIRequest(Protocol): @@ -11,8 +11,9 @@ def __call__( body: Optional[Union[str, bytes]] = None, raise_for_status: bool = True, method: str = "POST", + stream: bool = False, **kwargs, - ) -> requests.Response: ... + ) -> httpx2.Response: ... class APIClientGroup: diff --git a/src/dstack/api/server/_presets.py b/src/dstack/api/server/_presets.py index 432155d4c..2e41925bc 100644 --- a/src/dstack/api/server/_presets.py +++ b/src/dstack/api/server/_presets.py @@ -1,5 +1,7 @@ from typing import Iterator, Tuple +import httpx2 + from dstack._internal.core.errors import ClientError from dstack._internal.core.models.common import validate_extra_ignore from dstack._internal.core.models.presets import PresetSpec @@ -42,7 +44,14 @@ def get_files(self, project_name: str, name_or_id: str) -> Iterator[Tuple[str, b body=body.model_dump_json(), stream=True, ) - return _iter_archives(resp.iter_content(chunk_size=_STREAM_CHUNK_SIZE)) + return _iter_archives(_iter_chunks(resp)) + + +def _iter_chunks(resp: httpx2.Response) -> Iterator[bytes]: + try: + yield from resp.iter_bytes(chunk_size=_STREAM_CHUNK_SIZE) + except httpx2.RequestError as e: + raise ClientError(f"Failed to read preset files: {e!r}") from e def _iter_archives(chunks: Iterator[bytes]) -> Iterator[Tuple[str, bytes]]: diff --git a/src/tests/_internal/cli/services/presets/test_registry.py b/src/tests/_internal/cli/services/presets/test_registry.py index 8358a51ec..cabb1d21f 100644 --- a/src/tests/_internal/cli/services/presets/test_registry.py +++ b/src/tests/_internal/cli/services/presets/test_registry.py @@ -1,5 +1,4 @@ import io -import json import logging import tarfile from datetime import datetime @@ -9,7 +8,6 @@ from uuid import uuid4 import pytest -import requests import yaml from dstack._internal.cli.models.presets import PulledPreset @@ -329,7 +327,7 @@ def frame(path: str, blob: bytes) -> bytes: # Framed values are read across chunk boundaries, so a chunk size that # splits every frame is what proves the reader, not the framing. chunks = [stream[i : i + 3] for i in range(0, len(stream), 3)] - client, calls = self._client(SimpleNamespace(iter_content=lambda chunk_size: iter(chunks))) + client, calls = self._client(SimpleNamespace(iter_bytes=lambda chunk_size: iter(chunks))) got = list(client.get_files("main", "qwen38")) @@ -466,7 +464,9 @@ class TestPullPresetFromRegistry: ], ids=["no-config", "local-default"], ) - def test_pulls_from_sky_without_registry_credentials(self, tmp_path, monkeypatch, projects): + def test_pulls_from_sky_without_registry_credentials( + self, tmp_path, monkeypatch, http_mock, projects + ): base_url = registry_module.SKY_BASE_URL dstack_dir = tmp_path / ".dstack" dstack_dir.mkdir() @@ -479,8 +479,6 @@ def test_pulls_from_sky_without_registry_credentials(self, tmp_path, monkeypatch monkeypatch.setenv("DSTACK_SERVER_URL", "http://local-server") monkeypatch.setenv("DSTACK_PROJECT", "local") monkeypatch.setenv("DSTACK_TOKEN", "local-environment-token") - # Request preparation must not read the developer's own netrc credentials. - monkeypatch.setenv("NETRC", str(tmp_path / "no-netrc")) remote = _registry_preset( file_archives=[FileArchiveMapping(id=uuid4(), path="/app/a.txt")], file_mappings=[FilePathMapping(local_path="patch/a.txt", path="/app/a.txt")], @@ -491,32 +489,21 @@ def test_pulls_from_sky_without_registry_credentials(self, tmp_path, monkeypatch stream = ( len(file_path).to_bytes(4, "big") + file_path + len(blob).to_bytes(8, "big") + blob ) - requests_sent = [] - - def send(session, request, **kwargs): - # Inspect fully prepared requests, after session headers/environment - # handling, while keeping both real API calls off the network. - requests_sent.append(request) - assert request.method == "POST" - assert request.headers.get("Authorization") is None - response = requests.Response() - response.status_code = 200 - response.request = request - if request.url == f"{base_url}/api/project/dstack/presets/get": - assert json.loads(request.body) == {"name_or_id": "qwen38"} - response.raw = io.BytesIO(remote.model_dump_json().encode()) - else: - assert request.url == f"{base_url}/api/project/dstack/presets/get_files" - assert json.loads(request.body) == {"name_or_id": str(remote.id)} - response.raw = io.BytesIO(stream) - return response - - monkeypatch.setattr(requests.Session, "send", send) + get_url = f"{base_url}/api/project/dstack/presets/get" + get_files_url = f"{base_url}/api/project/dstack/presets/get_files" + http_mock.post(get_url, content=remote.model_dump_json().encode()) + http_mock.post(get_files_url, content=stream) store = PresetStore(tmp_path / "presets") pull_preset_from_registry(store, "dstack/qwen38") - assert len(requests_sent) == 2 + get_request, get_files_request = http_mock.request_history + assert str(get_request.url) == get_url + assert get_request.json() == {"name_or_id": "qwen38"} + assert str(get_files_request.url) == get_files_url + assert get_files_request.json() == {"name_or_id": str(remote.id)} + assert get_request.headers.get("Authorization") is None + assert get_files_request.headers.get("Authorization") is None pulled = get_or_error(store.get(str(remote.id))) assert pulled.name == "dstack/qwen38" assert Path(pulled.service.files[0].local_path).read_text() == "public preset file" diff --git a/src/tests/_internal/core/services/test_api_client.py b/src/tests/_internal/core/services/test_api_client.py index 94668481c..81d253b87 100644 --- a/src/tests/_internal/core/services/test_api_client.py +++ b/src/tests/_internal/core/services/test_api_client.py @@ -51,5 +51,5 @@ def test_token_alone_overrides_configured_token(self, monkeypatch): client, project_name = get_api_client() assert client.base_url == "https://server.example.com" - assert client._s.headers["Authorization"] == "Bearer environment-token" + assert client._client.headers["Authorization"] == "Bearer environment-token" assert project_name == "configured-project" diff --git a/src/tests/api/server/common.py b/src/tests/api/server/common.py index 3eda9873e..a5eb937ff 100644 --- a/src/tests/api/server/common.py +++ b/src/tests/api/server/common.py @@ -1,8 +1,7 @@ -import json from dataclasses import dataclass, field from typing import Any, Optional, Union -import requests +import httpx2 @dataclass @@ -18,12 +17,10 @@ def __call__( body: Optional[Union[str, bytes]] = None, raise_for_status: bool = True, method: str = "POST", + stream: bool = False, **kwargs, - ) -> requests.Response: + ) -> httpx2.Response: self.last_path = path self.last_body = body self.last_kwargs = kwargs - resp = requests.Response() - resp.status_code = 200 - resp._content = json.dumps(self.payload).encode("utf-8") - return resp + return httpx2.Response(200, json=self.payload) diff --git a/src/tests/api/server/test_api_client.py b/src/tests/api/server/test_api_client.py index 44b5e3f76..b660440be 100644 --- a/src/tests/api/server/test_api_client.py +++ b/src/tests/api/server/test_api_client.py @@ -1,30 +1,120 @@ -from unittest.mock import Mock, patch +import httpx2 +import pytest +from dstack._internal.core.errors import ClientError, URLNotFoundError +from dstack.api import server as server_module from dstack.api.server import APIClient +from tests.http_mock import HTTPMock -class TestAPIClientTransport: - def test_mounts_unix_socket_adapter(self): - session = Mock() - adapter = Mock() - with ( - patch("dstack.api.server.requests.session", return_value=session), - patch("dstack.api.server.requests_unixsocket.UnixAdapter", return_value=adapter), - ): - client = APIClient("http+unix://%2Frun%2Fdstack%2Fserver.sock", token="token") - - assert client.base_url == "http+unix://%2Frun%2Fdstack%2Fserver.sock" - session.mount.assert_called_once_with("http+unix://", adapter) - session.headers.update.assert_any_call({"Authorization": "Bearer token"}) - - def test_http_transport_does_not_mount_unix_socket_adapter(self): - session = Mock() - with ( - patch("dstack.api.server.requests.session", return_value=session), - patch("dstack.api.server.requests_unixsocket.UnixAdapter") as adapter_class, - ): - client = APIClient("https://server.example.com/") - - assert client.base_url == "https://server.example.com" - adapter_class.assert_not_called() - session.mount.assert_not_called() +class TestAPIClient: + @pytest.fixture(autouse=True) + def no_retry_sleep(self, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(server_module.time, "sleep", lambda _: None) + + def test_sends_requests_with_token(self, http_mock: HTTPMock): + http_mock.post("https://server.test/api/users/get_my_user", json={}) + client = APIClient("https://server.test/", token="token") + + client._request("/api/users/get_my_user", body="{}") + + request = http_mock.last_request + assert request.headers["Authorization"] == "Bearer token" + assert request.headers["Content-Type"] == "application/json" + assert request.content == b"{}" + assert request.timeout == {"connect": 15, "read": 600, "write": 600, "pool": 600} + + def test_sends_requests_over_unix_socket(self, http_mock: HTTPMock): + http_mock.post("http://localhost/prefix/api/users/get_my_user", json={}) + client = APIClient("http+unix://%2Frun%2Fdstack%2Fserver.sock/prefix", token="token") + + client._request("/api/users/get_my_user") + + assert client.base_url == "http+unix://%2Frun%2Fdstack%2Fserver.sock/prefix" + transport = client._client._transport + assert isinstance(transport, httpx2.HTTPTransport) + assert transport._pool._uds == "/run/dstack/server.sock" + assert http_mock.call_count == 1 + + def test_follows_redirects(self, http_mock: HTTPMock): + http_mock.post( + "http://server.test/api/users/get_my_user", + status_code=308, + headers={"Location": "https://server.test/api/users/get_my_user"}, + ) + http_mock.post("https://server.test/api/users/get_my_user", json={"ok": True}) + client = APIClient("http://server.test", token="token") + + resp = client._request("/api/users/get_my_user") + + assert resp.json() == {"ok": True} + assert http_mock.last_request.headers["Authorization"] == "Bearer token" + + def test_retries_connection_errors(self, http_mock: HTTPMock): + http_mock.post( + "https://server.test/api/users/get_my_user", + [{"exc": httpx2.ConnectError("refused")}, {"json": {}}], + ) + client = APIClient("https://server.test") + + client._request("/api/users/get_my_user") + + assert http_mock.call_count == 2 + + @pytest.mark.parametrize( + "exc", [httpx2.ConnectError("refused"), httpx2.ConnectTimeout("slow")] + ) + def test_raises_client_error_when_cannot_connect(self, http_mock: HTTPMock, exc: Exception): + http_mock.post("https://server.test/api/users/get_my_user", exc=exc) + client = APIClient("https://server.test") + + with pytest.raises(ClientError, match="Failed to connect to dstack server"): + client._request("/api/users/get_my_user") + + assert http_mock.call_count == server_module._MAX_RETRIES + + @pytest.mark.parametrize( + "exc", [httpx2.ReadTimeout("slow"), httpx2.RemoteProtocolError("broken")] + ) + def test_wraps_other_request_errors_without_retrying( + self, http_mock: HTTPMock, exc: Exception + ): + http_mock.post("https://server.test/api/users/get_my_user", exc=exc) + client = APIClient("https://server.test") + + with pytest.raises(ClientError, match="Failed to request") as exc_info: + client._request("/api/users/get_my_user") + + assert exc_info.value.__cause__ is exc + assert http_mock.call_count == 1 + + def test_raises_client_error_for_url_without_scheme(self, http_mock: HTTPMock): + client = APIClient("localhost:3000") + + with pytest.raises(ClientError, match="Failed to request"): + client._request("/api/users/get_my_user") + + assert not http_mock.called + + def test_maps_error_statuses(self, http_mock: HTTPMock): + http_mock.post("https://server.test/api/missing", status_code=404) + client = APIClient("https://server.test") + + with pytest.raises(URLNotFoundError): + client._request("/api/missing") + + +class TestParseBaseURL: + @pytest.mark.parametrize( + ("base_url", "expected"), + [ + ("https://server.test", ("https://server.test", None)), + ("http+unix://%2Frun%2Fserver.sock", ("http://localhost", "/run/server.sock")), + ( + "http+unix://%2Frun%2Fserver.sock/prefix", + ("http://localhost/prefix", "/run/server.sock"), + ), + ], + ) + def test_parses(self, base_url: str, expected: tuple): + assert server_module._parse_base_url(base_url) == expected From 458070854a0ce4b03337af958739a207cf344bd9 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:21:03 +0500 Subject: [PATCH 07/37] Test APIClient URL without scheme without http_mock --- src/tests/api/server/test_api_client.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/tests/api/server/test_api_client.py b/src/tests/api/server/test_api_client.py index b660440be..1c4b9ece7 100644 --- a/src/tests/api/server/test_api_client.py +++ b/src/tests/api/server/test_api_client.py @@ -88,14 +88,13 @@ def test_wraps_other_request_errors_without_retrying( assert exc_info.value.__cause__ is exc assert http_mock.call_count == 1 - def test_raises_client_error_for_url_without_scheme(self, http_mock: HTTPMock): + def test_raises_client_error_for_url_without_scheme(self): + # Without http_mock: httpx2's transport rejects the URL before any network access. client = APIClient("localhost:3000") - with pytest.raises(ClientError, match="Failed to request"): + with pytest.raises(ClientError, match="UnsupportedProtocol"): client._request("/api/users/get_my_user") - assert not http_mock.called - def test_maps_error_statuses(self, http_mock: HTTPMock): http_mock.post("https://server.test/api/missing", status_code=404) client = APIClient("https://server.test") From 591353202ac02a2a4d42ac14f555bc997739130f Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:35:37 +0500 Subject: [PATCH 08/37] Lower APIClient timeouts to 60s --- src/dstack/api/server/__init__.py | 3 +-- src/tests/api/server/test_api_client.py | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/dstack/api/server/__init__.py b/src/dstack/api/server/__init__.py index 02ce29751..c590562c1 100644 --- a/src/dstack/api/server/__init__.py +++ b/src/dstack/api/server/__init__.py @@ -38,8 +38,7 @@ _MAX_RETRIES = 3 _RETRY_INTERVAL = 1 -# Some requests take long, e.g. applying a plan. -_TIMEOUT = httpx2.Timeout(600, connect=15) +_TIMEOUT = httpx2.Timeout(60, connect=15) class APIClient: diff --git a/src/tests/api/server/test_api_client.py b/src/tests/api/server/test_api_client.py index 1c4b9ece7..b0f658a08 100644 --- a/src/tests/api/server/test_api_client.py +++ b/src/tests/api/server/test_api_client.py @@ -22,7 +22,7 @@ def test_sends_requests_with_token(self, http_mock: HTTPMock): assert request.headers["Authorization"] == "Bearer token" assert request.headers["Content-Type"] == "application/json" assert request.content == b"{}" - assert request.timeout == {"connect": 15, "read": 600, "write": 600, "pool": 600} + assert request.timeout == {"connect": 15, "read": 60, "write": 60, "pool": 60} def test_sends_requests_over_unix_socket(self, http_mock: HTTPMock): http_mock.post("http://localhost/prefix/api/users/get_my_user", json={}) From e4bb97db1cb8e1a4c36c6cf5c87a9e969c5c2d4f Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:43:15 +0500 Subject: [PATCH 09/37] Require an explicit timeout for HTTP clients --- .../core/backends/cloudrift/api_client.py | 3 +-- .../_internal/core/backends/crusoe/resources.py | 6 ++---- .../core/backends/daytona/api_client.py | 3 +-- .../backends/digitalocean_base/api_client.py | 5 ++--- .../core/backends/hotaisle/api_client.py | 4 +--- .../core/backends/jarvislabs/api_client.py | 3 +-- .../core/backends/lambdalabs/api_client.py | 3 +-- .../_internal/core/backends/lium/api_client.py | 3 +-- .../core/backends/massedcompute/api_client.py | 3 +-- .../_internal/core/backends/runpod/api_client.py | 2 +- .../_internal/core/backends/seeweb/api_client.py | 3 +-- .../_internal/core/backends/vultr/api_client.py | 3 +-- .../proxy/gateway/services/server_client.py | 5 ++++- .../services/jobs/job_replica_http_client.py | 7 ++++++- .../_internal/server/services/runner/client.py | 15 +++++++-------- src/dstack/_internal/utils/http.py | 11 ++++++----- .../services/proxy/routers/test_service_proxy.py | 2 +- src/tests/_internal/utils/test_http.py | 16 +++++++++------- 18 files changed, 47 insertions(+), 50 deletions(-) diff --git a/src/dstack/_internal/core/backends/cloudrift/api_client.py b/src/dstack/_internal/core/backends/cloudrift/api_client.py index 8967d252e..d422cde26 100644 --- a/src/dstack/_internal/core/backends/cloudrift/api_client.py +++ b/src/dstack/_internal/core/backends/cloudrift/api_client.py @@ -21,7 +21,7 @@ class RiftClient: def __init__(self, api_key: Optional[str] = None): self.public_api_root = os.path.join(CLOUDRIFT_SERVER_ADDRESS, "api/v1") self.api_key = api_key - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=15) def close(self) -> None: self._client.close() @@ -204,7 +204,6 @@ def _make_request( full_url, headers=headers, json={"version": version, "data": data}, - timeout=15, **kwargs, ) diff --git a/src/dstack/_internal/core/backends/crusoe/resources.py b/src/dstack/_internal/core/backends/crusoe/resources.py index b726960f8..80793c686 100644 --- a/src/dstack/_internal/core/backends/crusoe/resources.py +++ b/src/dstack/_internal/core/backends/crusoe/resources.py @@ -25,7 +25,7 @@ def __init__(self, creds: CrusoeAccessKeyCreds, project_id: str): self.access_key = creds.access_key self.secret_key = creds.secret_key self.project_id = project_id - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=REQUEST_TIMEOUT) def close(self) -> None: self._client.close() @@ -60,9 +60,7 @@ def _request( headers["Content-Type"] = "application/json" url = f"{API_URL}{API_VERSION}{path}" - resp = self._client.request( - method, url, headers=headers, params=params, json=body, timeout=REQUEST_TIMEOUT - ) + resp = self._client.request(method, url, headers=headers, params=params, json=body) if resp.status_code >= 400: _raise_api_error(resp) return resp diff --git a/src/dstack/_internal/core/backends/daytona/api_client.py b/src/dstack/_internal/core/backends/daytona/api_client.py index 674c66533..569b1e7c9 100644 --- a/src/dstack/_internal/core/backends/daytona/api_client.py +++ b/src/dstack/_internal/core/backends/daytona/api_client.py @@ -24,7 +24,7 @@ class DaytonaNotFoundError(DaytonaAPIError): class DaytonaAPIClient: def __init__(self, api_key: str): self.api_key = api_key - self._client = HTTPClient() + self._client = HTTPClient(timeout=REQUEST_TIMEOUT_SECONDS) def close(self) -> None: self._client.close() @@ -197,7 +197,6 @@ def _request( headers={"Authorization": f"Bearer {self.api_key}"}, json=json, params=params, - timeout=REQUEST_TIMEOUT_SECONDS, follow_redirects=False, ) except httpx2.TimeoutException as e: diff --git a/src/dstack/_internal/core/backends/digitalocean_base/api_client.py b/src/dstack/_internal/core/backends/digitalocean_base/api_client.py index 03871e752..f4ba183b6 100644 --- a/src/dstack/_internal/core/backends/digitalocean_base/api_client.py +++ b/src/dstack/_internal/core/backends/digitalocean_base/api_client.py @@ -14,7 +14,7 @@ class DigitalOceanAPIClient: def __init__(self, api_key: str, api_url: str): self.api_key = api_key self.base_url = api_url - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=30) def close(self) -> None: self._client.close() @@ -91,7 +91,7 @@ def delete_droplet(self, droplet_id: str) -> None: response.raise_for_status() def _make_request( - self, method: str, endpoint: str, json: Optional[Dict[str, Any]] = None, timeout: int = 30 + self, method: str, endpoint: str, json: Optional[Dict[str, Any]] = None ) -> httpx2.Response: url = f"{self.base_url}{endpoint}" headers = { @@ -103,6 +103,5 @@ def _make_request( url=url, headers=headers, json=json, - timeout=timeout, ) return response diff --git a/src/dstack/_internal/core/backends/hotaisle/api_client.py b/src/dstack/_internal/core/backends/hotaisle/api_client.py index aa3192902..861324752 100644 --- a/src/dstack/_internal/core/backends/hotaisle/api_client.py +++ b/src/dstack/_internal/core/backends/hotaisle/api_client.py @@ -16,7 +16,7 @@ class HotAisleAPIClient: def __init__(self, api_key: str, team_handle: str): self.api_key = api_key self.team_handle = team_handle - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=30) def close(self) -> None: self._client.close() @@ -131,7 +131,6 @@ def _make_request( url: str, json: Optional[dict[str, Any]] = None, params: Optional[dict[str, str]] = None, - timeout: int = 30, ) -> httpx2.Response: headers = { "accept": "application/json", @@ -146,5 +145,4 @@ def _make_request( headers=headers, json=json, params=params, - timeout=timeout, ) diff --git a/src/dstack/_internal/core/backends/jarvislabs/api_client.py b/src/dstack/_internal/core/backends/jarvislabs/api_client.py index 87deb5b20..a55ae48b5 100644 --- a/src/dstack/_internal/core/backends/jarvislabs/api_client.py +++ b/src/dstack/_internal/core/backends/jarvislabs/api_client.py @@ -21,7 +21,7 @@ class JarvisLabsNotFoundError(BackendError): class JarvisLabsAPIClient: def __init__(self, api_key: str): self.api_key = api_key - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=TIMEOUT) def close(self) -> None: self._client.close() @@ -215,7 +215,6 @@ def _make_request( headers={"Authorization": f"Bearer {self.api_key}"}, json=json, params=params, - timeout=TIMEOUT, ) except httpx2.HTTPError as e: raise BackendError(f"JarvisLabs request failed: {e}") from e diff --git a/src/dstack/_internal/core/backends/lambdalabs/api_client.py b/src/dstack/_internal/core/backends/lambdalabs/api_client.py index cf56676ec..2418a0552 100644 --- a/src/dstack/_internal/core/backends/lambdalabs/api_client.py +++ b/src/dstack/_internal/core/backends/lambdalabs/api_client.py @@ -10,7 +10,7 @@ class LambdaAPIClient: def __init__(self, api_key: str): self.api_key = api_key - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=120) def close(self) -> None: self._client.close() @@ -85,7 +85,6 @@ def _make_request(self, method: str, path: str, data: Any = None): url=API_URL + path, json=data, headers={"Authorization": f"Bearer {self.api_key}"}, - timeout=120, ) def _url(self, path: str) -> str: diff --git a/src/dstack/_internal/core/backends/lium/api_client.py b/src/dstack/_internal/core/backends/lium/api_client.py index 0a1286b05..525365cfb 100644 --- a/src/dstack/_internal/core/backends/lium/api_client.py +++ b/src/dstack/_internal/core/backends/lium/api_client.py @@ -28,7 +28,7 @@ def __init__( class LiumAPIClient: def __init__(self, api_key: str): self.api_key = api_key - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=REQUEST_TIMEOUT_SECONDS) def close(self) -> None: self._client.close() @@ -129,7 +129,6 @@ def _make_request( headers={"X-API-Key": self.api_key, **(headers or {})}, json=json, params=params, - timeout=REQUEST_TIMEOUT_SECONDS, follow_redirects=False, ) except httpx2.TimeoutException: diff --git a/src/dstack/_internal/core/backends/massedcompute/api_client.py b/src/dstack/_internal/core/backends/massedcompute/api_client.py index d36eb2439..dd3ef1aef 100644 --- a/src/dstack/_internal/core/backends/massedcompute/api_client.py +++ b/src/dstack/_internal/core/backends/massedcompute/api_client.py @@ -48,7 +48,7 @@ class _TerminateRequest(TypedDict, closed=True): class MassedComputeAPIClient: def __init__(self, api_key: str): self.api_key = api_key - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=30) def close(self) -> None: self._client.close() @@ -110,7 +110,6 @@ def _request( method, API_URL + path, json=payload, - timeout=30, follow_redirects=False, # A redirect can replay a launch POST. headers={"Authorization": f"Bearer {self.api_key}"}, ) diff --git a/src/dstack/_internal/core/backends/runpod/api_client.py b/src/dstack/_internal/core/backends/runpod/api_client.py index 51d52b504..534adc0d1 100644 --- a/src/dstack/_internal/core/backends/runpod/api_client.py +++ b/src/dstack/_internal/core/backends/runpod/api_client.py @@ -218,6 +218,7 @@ def __init__(self, api_key: str): self._client = HTTPClient( headers={"Authorization": f"Bearer {api_key}"}, follow_redirects=True, + timeout=REQUEST_TIMEOUT, ) def close(self) -> None: @@ -415,7 +416,6 @@ def _make_v2_request( response = self._client.request( method=method, url=url, - timeout=REQUEST_TIMEOUT, json=json, params=params, ) diff --git a/src/dstack/_internal/core/backends/seeweb/api_client.py b/src/dstack/_internal/core/backends/seeweb/api_client.py index 699bc581a..67a46301c 100644 --- a/src/dstack/_internal/core/backends/seeweb/api_client.py +++ b/src/dstack/_internal/core/backends/seeweb/api_client.py @@ -33,7 +33,7 @@ class SeewebApiClient: def __init__(self, api_token: str): self.api_token = api_token - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=TIMEOUT) def close(self) -> None: self._client.close() @@ -47,7 +47,6 @@ def _request( url=API_URL + path, headers={"X-APITOKEN": self.api_token}, json=json, - timeout=TIMEOUT, ) except httpx2.HTTPError as e: raise BackendError(f"Seeweb API request failed: {e}") from e diff --git a/src/dstack/_internal/core/backends/vultr/api_client.py b/src/dstack/_internal/core/backends/vultr/api_client.py index ace948b00..944e1ce70 100644 --- a/src/dstack/_internal/core/backends/vultr/api_client.py +++ b/src/dstack/_internal/core/backends/vultr/api_client.py @@ -12,7 +12,7 @@ class VultrApiClient: def __init__(self, api_key: str): self.api_key = api_key - self._client = HTTPClient(follow_redirects=True) + self._client = HTTPClient(follow_redirects=True, timeout=30) def close(self) -> None: self._client.close() @@ -101,7 +101,6 @@ def _make_request(self, method: str, path: str, data: Any = None) -> httpx2.Resp url=API_URL + path, json=data, headers={"Authorization": f"Bearer {self.api_key}"}, - timeout=30, ) response.raise_for_status() return response diff --git a/src/dstack/_internal/proxy/gateway/services/server_client.py b/src/dstack/_internal/proxy/gateway/services/server_client.py index ad21e8e7a..8bbf07111 100644 --- a/src/dstack/_internal/proxy/gateway/services/server_client.py +++ b/src/dstack/_internal/proxy/gateway/services/server_client.py @@ -11,6 +11,7 @@ logger = logging.getLogger(__name__) BASE_URL = "http://dstack/" # any hostname will work +TIMEOUT = 5 @dataclass @@ -37,7 +38,7 @@ class HTTPMultiClient(AsyncHTTPClient): """ def __init__(self, sockets_dir: Path): - super().__init__(base_url=BASE_URL) + super().__init__(base_url=BASE_URL, timeout=TIMEOUT) self._sockets_dir = sockets_dir.expanduser() self._clients_cache: Dict[str, CachedClientInfo] = {} @@ -90,6 +91,8 @@ def _make_client(socket: Path) -> CachedClientInfo: client = AsyncHTTPClient( transport=httpx2.AsyncHTTPTransport(uds=str(socket.absolute())), base_url=BASE_URL, + # Unused: the requests come from the outer client with its timeout. + timeout=TIMEOUT, ) return CachedClientInfo( client=client, diff --git a/src/dstack/_internal/server/services/jobs/job_replica_http_client.py b/src/dstack/_internal/server/services/jobs/job_replica_http_client.py index 30e3327b2..8c1594e8d 100644 --- a/src/dstack/_internal/server/services/jobs/job_replica_http_client.py +++ b/src/dstack/_internal/server/services/jobs/job_replica_http_client.py @@ -10,12 +10,17 @@ from dstack._internal.server.services.jobs.job_replica_tunnel import get_service_replica_tunnel from dstack._internal.utils.http import AsyncHTTPClient +# Callers pass longer per-request timeouts where needed. +_TIMEOUT = 5 + @asynccontextmanager async def get_service_replica_http_client_over_uds( uds_path: Path, ) -> AsyncGenerator[AsyncClient, None]: - async with AsyncHTTPClient(transport=AsyncHTTPTransport(uds=str(uds_path))) as client: + async with AsyncHTTPClient( + transport=AsyncHTTPTransport(uds=str(uds_path)), timeout=_TIMEOUT + ) as client: yield client diff --git a/src/dstack/_internal/server/services/runner/client.py b/src/dstack/_internal/server/services/runner/client.py index d1ccf6a87..67e21621a 100644 --- a/src/dstack/_internal/server/services/runner/client.py +++ b/src/dstack/_internal/server/services/runner/client.py @@ -255,7 +255,6 @@ def get_metrics(self, job_submission_id: uuid.UUID) -> Optional[MetricsResponse] resp = self._client.get( "/api/metrics", params={"job_submission_id": str(job_submission_id)}, - timeout=REQUEST_TIMEOUT, ) if resp.status_code == 404: return None @@ -304,7 +303,6 @@ def submit_job( "/api/submit", content=body.json_for_runner(), headers={"Content-Type": "application/json"}, - timeout=REQUEST_TIMEOUT, ) self._raise_for_status(resp) @@ -323,7 +321,7 @@ def upload_code(self, file: Union[BinaryIO, bytes]): self._raise_for_status(resp) def run_job(self) -> Optional[JobInfoResponse]: - resp = self._client.post("/api/run", timeout=REQUEST_TIMEOUT) + resp = self._client.post("/api/run") self._raise_for_status(resp) if not _is_json_response(resp): # Old runner or runner failed to get job info @@ -334,7 +332,6 @@ def pull(self, job_submission_id: uuid.UUID, timestamp: int) -> PullResponse: resp = self._client.get( "/api/pull", params={"job_submission_id": str(job_submission_id), "timestamp": timestamp}, - timeout=REQUEST_TIMEOUT, ) self._raise_for_job_submission_status(resp) return self._response(PullResponse, resp) @@ -343,7 +340,6 @@ def stop(self, job_submission_id: uuid.UUID): resp = self._client.post( "/api/stop", params={"job_submission_id": str(job_submission_id)}, - timeout=REQUEST_TIMEOUT, ) self._raise_for_job_submission_status(resp) @@ -364,7 +360,7 @@ def _raise_for_job_submission_status(self, response: httpx2.Response) -> None: self._raise_for_status(response) def _healthcheck(self) -> HealthcheckResponse: - resp = self._client.get("/api/healthcheck", timeout=REQUEST_TIMEOUT) + resp = self._client.get("/api/healthcheck") self._raise_for_status(resp) return self._response(HealthcheckResponse, resp) @@ -741,7 +737,7 @@ def _request( json = body.model_dump() else: json = None - resp = self._client.request(method, path, json=json, timeout=REQUEST_TIMEOUT) + resp = self._client.request(method, path, json=json) if raise_for_status: self._raise_for_status(resp) return resp @@ -791,10 +787,13 @@ def _make_client(port: Optional[int], hostname: str, uds: Optional[PathLike]) -> if uds is not None: return HTTPClient( base_url="http://localhost", + timeout=REQUEST_TIMEOUT, follow_redirects=True, transport=httpx2.HTTPTransport(uds=str(uds)), ) - return HTTPClient(base_url=f"http://{hostname}:{port}", follow_redirects=True) + return HTTPClient( + base_url=f"http://{hostname}:{port}", timeout=REQUEST_TIMEOUT, follow_redirects=True + ) def healthcheck_response_to_instance_check( diff --git a/src/dstack/_internal/utils/http.py b/src/dstack/_internal/utils/http.py index bd8958d0c..713cde482 100644 --- a/src/dstack/_internal/utils/http.py +++ b/src/dstack/_internal/utils/http.py @@ -9,8 +9,7 @@ USER_AGENT = f"dstack/{version.__version__}" -# The httpx2 defaults. -_DEFAULT_TIMEOUT = httpx2.Timeout(5.0) +# The httpx2 default. _DEFAULT_LIMITS = httpx2.Limits(max_connections=100, max_keepalive_connections=20) @@ -18,9 +17,11 @@ class HTTPClient(httpx2.Client): """ The base class for dstack's sync HTTP clients: an `httpx2.Client` with dstack defaults. + `timeout` is required: a number sets the connect, read, write, and pool timeouts, each of + which limits one wait (e.g. for the next response bytes), not the whole request. `verify=True` trusts the system CA certificates, or the certifi bundle on systems without them (see `get_default_ssl_context()`). Requests send `User-Agent: dstack/` unless - `headers` set another one. Other defaults are httpx2's: a 5s timeout and no redirects. + `headers` set another one. Redirects are not followed by default, as in httpx2. """ def __init__( @@ -28,7 +29,7 @@ def __init__( *, base_url: str = "", headers: Optional[Mapping[str, str]] = None, - timeout: Union[httpx2.Timeout, float, None] = _DEFAULT_TIMEOUT, + timeout: Union[httpx2.Timeout, float, None], verify: Union[ssl.SSLContext, bool] = True, follow_redirects: bool = False, limits: httpx2.Limits = _DEFAULT_LIMITS, @@ -56,7 +57,7 @@ def __init__( *, base_url: str = "", headers: Optional[Mapping[str, str]] = None, - timeout: Union[httpx2.Timeout, float, None] = _DEFAULT_TIMEOUT, + timeout: Union[httpx2.Timeout, float, None], verify: Union[ssl.SSLContext, bool] = True, follow_redirects: bool = False, limits: httpx2.Limits = _DEFAULT_LIMITS, diff --git a/src/tests/_internal/server/services/proxy/routers/test_service_proxy.py b/src/tests/_internal/server/services/proxy/routers/test_service_proxy.py index a9602f689..e32cf369a 100644 --- a/src/tests/_internal/server/services/proxy/routers/test_service_proxy.py +++ b/src/tests/_internal/server/services/proxy/routers/test_service_proxy.py @@ -59,7 +59,7 @@ def mock_replica_client_path_reporter() -> Generator[None, None, None]: app = FastAPI() app.get("{path:path}")(lambda path: PlainTextResponse(path)) - client = ServiceClient(base_url="http://test/", transport=httpx2.ASGITransport(app)) + client = ServiceClient(base_url="http://test/", timeout=5, transport=httpx2.ASGITransport(app)) with patch( "dstack._internal.proxy.lib.services.service_connection.ServiceConnectionPool.get_or_add" ) as add_connection_mock: diff --git a/src/tests/_internal/utils/test_http.py b/src/tests/_internal/utils/test_http.py index b96291ae3..6e70c51d0 100644 --- a/src/tests/_internal/utils/test_http.py +++ b/src/tests/_internal/utils/test_http.py @@ -11,25 +11,27 @@ class TestHTTPClient: def test_sends_dstack_user_agent(self): transport = httpx2.MockTransport(_echo_user_agent) - with HTTPClient(transport=transport) as client: + with HTTPClient(timeout=5, transport=transport) as client: assert client.get("http://test/").text == USER_AGENT def test_keeps_user_agent_from_headers(self): transport = httpx2.MockTransport(_echo_user_agent) - with HTTPClient(transport=transport, headers={"user-agent": "custom"}) as client: + with HTTPClient( + timeout=5, transport=transport, headers={"user-agent": "custom"} + ) as client: assert client.get("http://test/").text == "custom" def test_uses_default_ssl_context(self, monkeypatch: pytest.MonkeyPatch): ctx = ssl.create_default_context() monkeypatch.setattr(http, "get_default_ssl_context", lambda: ctx) - assert _get_ssl_context(HTTPClient()) is ctx + assert _get_ssl_context(HTTPClient(timeout=5)) is ctx @pytest.mark.parametrize("verify", [False, ssl.create_default_context()]) def test_keeps_explicit_verify( self, monkeypatch: pytest.MonkeyPatch, verify: Union[ssl.SSLContext, bool] ): monkeypatch.setattr(http, "get_default_ssl_context", _fail) - ctx = _get_ssl_context(HTTPClient(verify=verify)) + ctx = _get_ssl_context(HTTPClient(timeout=5, verify=verify)) if isinstance(verify, ssl.SSLContext): assert ctx is verify else: @@ -37,7 +39,7 @@ def test_keeps_explicit_verify( def test_does_not_build_ssl_context_with_transport(self, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(http, "get_default_ssl_context", _fail) - HTTPClient(transport=httpx2.MockTransport(_echo_user_agent)) + HTTPClient(timeout=5, transport=httpx2.MockTransport(_echo_user_agent)) class TestAsyncHTTPClient: @@ -46,13 +48,13 @@ async def test_sends_dstack_user_agent(self): async def handler(request: httpx2.Request) -> httpx2.Response: return _echo_user_agent(request) - async with AsyncHTTPClient(transport=httpx2.MockTransport(handler)) as client: + async with AsyncHTTPClient(timeout=5, transport=httpx2.MockTransport(handler)) as client: assert (await client.get("http://test/")).text == USER_AGENT def test_uses_default_ssl_context(self, monkeypatch: pytest.MonkeyPatch): ctx = ssl.create_default_context() monkeypatch.setattr(http, "get_default_ssl_context", lambda: ctx) - assert _get_ssl_context(AsyncHTTPClient()) is ctx + assert _get_ssl_context(AsyncHTTPClient(timeout=5)) is ctx def _echo_user_agent(request: httpx2.Request) -> httpx2.Response: From d6dc7bb0e1208085fed305bb17e25dba93f321e7 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:51:22 +0500 Subject: [PATCH 10/37] Close gateway clients when closing gateway connections AsyncClientWrapper closed the client from __del__, which needs a running loop and leaves the close task unreferenced. --- .../server/services/gateways/client.py | 14 ++++------- .../server/services/gateways/connection.py | 1 + .../services/gateways/test_connection.py | 24 +++++++++++++++++++ 3 files changed, 29 insertions(+), 10 deletions(-) create mode 100644 src/tests/_internal/server/services/gateways/test_connection.py diff --git a/src/dstack/_internal/server/services/gateways/client.py b/src/dstack/_internal/server/services/gateways/client.py index 2213dcdfa..08f265a2c 100644 --- a/src/dstack/_internal/server/services/gateways/client.py +++ b/src/dstack/_internal/server/services/gateways/client.py @@ -1,4 +1,3 @@ -import asyncio import uuid from typing import Optional @@ -46,10 +45,13 @@ def __init__(self, uds: Optional[str] = None, port: Optional[int] = None): self.base_url = "http://gateway" if uds else f"http://localhost:{port}" # We set large timeout because service registration can take time. # Consider making gateway API async to avoid long-running requests. - self._client = AsyncClientWrapper( + self._client = AsyncHTTPClient( transport=httpx2.AsyncHTTPTransport(uds=uds) if uds else None, timeout=120 ) + async def aclose(self) -> None: + await self._client.aclose() + async def register_service( self, project: str, @@ -320,11 +322,3 @@ def get_gateway_endpoint_domain(service_domain: str) -> str: def gateway_error(data: dict) -> GatewayError: return GatewayError(msg=data["detail"]) - - -class AsyncClientWrapper(AsyncHTTPClient): - def __del__(self): - try: - asyncio.get_running_loop().create_task(self.aclose()) - except Exception: - pass diff --git a/src/dstack/_internal/server/services/gateways/connection.py b/src/dstack/_internal/server/services/gateways/connection.py index 555f9aaa0..cd502b5d0 100644 --- a/src/dstack/_internal/server/services/gateways/connection.py +++ b/src/dstack/_internal/server/services/gateways/connection.py @@ -110,6 +110,7 @@ async def _open_tunnel(self) -> None: async def close(self) -> None: async with self._lock.writer_lock: + await self._client.aclose() await self.tunnel.aclose() shutil.rmtree(self.connection_dir, ignore_errors=True) diff --git a/src/tests/_internal/server/services/gateways/test_connection.py b/src/tests/_internal/server/services/gateways/test_connection.py new file mode 100644 index 000000000..66070d9a8 --- /dev/null +++ b/src/tests/_internal/server/services/gateways/test_connection.py @@ -0,0 +1,24 @@ +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest + +from dstack._internal.server import settings +from dstack._internal.server.services.gateways.connection import GatewayConnection + + +class TestGatewayConnection: + @pytest.mark.asyncio + async def test_close_closes_client_and_tunnel( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ): + monkeypatch.setattr(settings, "SERVER_DIR_PATH", tmp_path) + conn = GatewayConnection(ip_address="10.0.0.1", id_rsa="key", server_port=3000) + (tmp_path / "gateway-connections" / "10.0.0.1").mkdir(parents=True) + tunnel_aclose = AsyncMock() + monkeypatch.setattr(conn.tunnel, "aclose", tunnel_aclose) + + await conn.close() + + assert conn._client._client.is_closed + tunnel_aclose.assert_awaited_once() From 8545a7bead08580e3ff6ef43645fba1abea8f837 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 15:55:11 +0500 Subject: [PATCH 11/37] Fix docstring --- src/dstack/api/server/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dstack/api/server/__init__.py b/src/dstack/api/server/__init__.py index c590562c1..c5dced76d 100644 --- a/src/dstack/api/server/__init__.py +++ b/src/dstack/api/server/__init__.py @@ -181,7 +181,7 @@ def _request( **kwargs, ) -> httpx2.Response: """ - Raises only dstack errors. With `stream=True`, the caller reads the response body, + With `stream=True`, the caller reads the response body, e.g. with `iter_bytes()`, and handles `httpx2.RequestError` while reading it. """ path = path.lstrip("/") From 642dc47d4fd198e5c148d59ea8a8a394e8d4994c Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:07:03 +0500 Subject: [PATCH 12/37] Don't load CA certificates for plain HTTP clients Runner and shim clients are created per call, and loading the CA bundle takes about 5 ms on Linux. --- .../proxy/gateway/services/server_client.py | 7 ++++--- .../proxy/lib/services/service_connection.py | 5 ++--- .../_internal/server/services/gateways/client.py | 7 ++++--- .../server/services/jobs/job_replica_http_client.py | 6 +++--- .../server/services/jobs/server_connection.py | 4 ++-- .../_internal/server/services/runner/client.py | 9 ++++++--- src/dstack/_internal/utils/http.py | 13 +++++++++++++ src/dstack/api/server/__init__.py | 4 ++-- src/tests/_internal/utils/test_http.py | 9 +++++++++ 9 files changed, 45 insertions(+), 19 deletions(-) diff --git a/src/dstack/_internal/proxy/gateway/services/server_client.py b/src/dstack/_internal/proxy/gateway/services/server_client.py index 8bbf07111..cc8f8c94f 100644 --- a/src/dstack/_internal/proxy/gateway/services/server_client.py +++ b/src/dstack/_internal/proxy/gateway/services/server_client.py @@ -7,7 +7,7 @@ import httpx2 -from dstack._internal.utils.http import AsyncHTTPClient +from dstack._internal.utils.http import AsyncHTTPClient, make_async_uds_transport logger = logging.getLogger(__name__) BASE_URL = "http://dstack/" # any hostname will work @@ -38,7 +38,8 @@ class HTTPMultiClient(AsyncHTTPClient): """ def __init__(self, sockets_dir: Path): - super().__init__(base_url=BASE_URL, timeout=TIMEOUT) + # Sends nothing itself, so it needs no SSL context. + super().__init__(base_url=BASE_URL, timeout=TIMEOUT, verify=False) self._sockets_dir = sockets_dir.expanduser() self._clients_cache: Dict[str, CachedClientInfo] = {} @@ -89,7 +90,7 @@ def _iter_clients_rand(self) -> Generator[CachedClientInfo, None, None]: @staticmethod def _make_client(socket: Path) -> CachedClientInfo: client = AsyncHTTPClient( - transport=httpx2.AsyncHTTPTransport(uds=str(socket.absolute())), + transport=make_async_uds_transport(str(socket.absolute())), base_url=BASE_URL, # Unused: the requests come from the outer client with its timeout. timeout=TIMEOUT, diff --git a/src/dstack/_internal/proxy/lib/services/service_connection.py b/src/dstack/_internal/proxy/lib/services/service_connection.py index 829feabf9..db6215a31 100644 --- a/src/dstack/_internal/proxy/lib/services/service_connection.py +++ b/src/dstack/_internal/proxy/lib/services/service_connection.py @@ -6,7 +6,6 @@ from typing import Dict, Optional import httpx2 -from httpx2 import AsyncHTTPTransport from dstack._internal.core.services.ssh.tunnel import ( SSH_DEFAULT_OPTIONS, @@ -19,7 +18,7 @@ from dstack._internal.proxy.lib.models import Project, Replica, Service from dstack._internal.proxy.lib.repo import BaseProxyRepo from dstack._internal.utils.common import get_or_error, run_async -from dstack._internal.utils.http import AsyncHTTPClient +from dstack._internal.utils.http import AsyncHTTPClient, make_async_uds_transport from dstack._internal.utils.logging import get_logger from dstack._internal.utils.path import FileContent @@ -101,7 +100,7 @@ def __init__( background=not (self._auto_reconnect or replica.ssh_head_proxy is not None), ) self._client = ServiceClient( - transport=AsyncHTTPTransport(uds=str(self._app_socket_path)), + transport=make_async_uds_transport(str(self._app_socket_path)), # The hostname in base_url is there for troubleshooting, as it may appear in # logs and in the Host header. The actual destination is the Unix socket. base_url=f"http://{replica.id}-{service.run_name}/", diff --git a/src/dstack/_internal/server/services/gateways/client.py b/src/dstack/_internal/server/services/gateways/client.py index 08f265a2c..d708831ef 100644 --- a/src/dstack/_internal/server/services/gateways/client.py +++ b/src/dstack/_internal/server/services/gateways/client.py @@ -1,7 +1,6 @@ import uuid from typing import Optional -import httpx2 from pydantic import TypeAdapter from dstack._internal.core.consts import DSTACK_RUNNER_SSH_PORT @@ -27,7 +26,7 @@ from dstack._internal.proxy.gateway.schemas.services import ServiceListItem, ServiceListResponse from dstack._internal.proxy.gateway.schemas.state import StateSummaryResponse from dstack._internal.proxy.gateway.schemas.stats import ServiceStats -from dstack._internal.utils.http import AsyncHTTPClient +from dstack._internal.utils.http import AsyncHTTPClient, make_async_uds_transport class GatewayClient: @@ -46,7 +45,9 @@ def __init__(self, uds: Optional[str] = None, port: Optional[int] = None): # We set large timeout because service registration can take time. # Consider making gateway API async to avoid long-running requests. self._client = AsyncHTTPClient( - transport=httpx2.AsyncHTTPTransport(uds=uds) if uds else None, timeout=120 + transport=make_async_uds_transport(uds) if uds else None, + timeout=120, + verify=False, # plain HTTP, no need to build an SSL context ) async def aclose(self) -> None: diff --git a/src/dstack/_internal/server/services/jobs/job_replica_http_client.py b/src/dstack/_internal/server/services/jobs/job_replica_http_client.py index 8c1594e8d..af6c7a025 100644 --- a/src/dstack/_internal/server/services/jobs/job_replica_http_client.py +++ b/src/dstack/_internal/server/services/jobs/job_replica_http_client.py @@ -4,11 +4,11 @@ from contextlib import asynccontextmanager from pathlib import Path -from httpx2 import AsyncClient, AsyncHTTPTransport +from httpx2 import AsyncClient from dstack._internal.server.models import JobModel from dstack._internal.server.services.jobs.job_replica_tunnel import get_service_replica_tunnel -from dstack._internal.utils.http import AsyncHTTPClient +from dstack._internal.utils.http import AsyncHTTPClient, make_async_uds_transport # Callers pass longer per-request timeouts where needed. _TIMEOUT = 5 @@ -19,7 +19,7 @@ async def get_service_replica_http_client_over_uds( uds_path: Path, ) -> AsyncGenerator[AsyncClient, None]: async with AsyncHTTPClient( - transport=AsyncHTTPTransport(uds=str(uds_path)), timeout=_TIMEOUT + transport=make_async_uds_transport(str(uds_path)), timeout=_TIMEOUT ) as client: yield client diff --git a/src/dstack/_internal/server/services/jobs/server_connection.py b/src/dstack/_internal/server/services/jobs/server_connection.py index 798c85c1d..eb76dee30 100644 --- a/src/dstack/_internal/server/services/jobs/server_connection.py +++ b/src/dstack/_internal/server/services/jobs/server_connection.py @@ -22,7 +22,7 @@ from dstack._internal.server import settings from dstack._internal.server.models import JobModel from dstack._internal.server.services.ssh import get_container_ssh_credentials -from dstack._internal.utils.http import AsyncHTTPClient +from dstack._internal.utils.http import AsyncHTTPClient, make_async_uds_transport from dstack._internal.utils.logging import get_logger from dstack._internal.utils.path import make_tmp_symlink_to_dir @@ -153,7 +153,7 @@ async def close(self) -> None: shutil.rmtree(self._connection_dir, ignore_errors=True) async def _server_is_reachable(self) -> bool: - transport = httpx2.AsyncHTTPTransport(uds=str(self._probe_socket_path)) + transport = make_async_uds_transport(str(self._probe_socket_path)) try: async with AsyncHTTPClient( transport=transport, diff --git a/src/dstack/_internal/server/services/runner/client.py b/src/dstack/_internal/server/services/runner/client.py index 67e21621a..b1d929ace 100644 --- a/src/dstack/_internal/server/services/runner/client.py +++ b/src/dstack/_internal/server/services/runner/client.py @@ -48,7 +48,7 @@ TaskTerminateRequest, ) from dstack._internal.utils.common import get_or_error -from dstack._internal.utils.http import HTTPClient +from dstack._internal.utils.http import HTTPClient, make_uds_transport from dstack._internal.utils.logging import get_logger from dstack._internal.utils.path import PathLike @@ -789,10 +789,13 @@ def _make_client(port: Optional[int], hostname: str, uds: Optional[PathLike]) -> base_url="http://localhost", timeout=REQUEST_TIMEOUT, follow_redirects=True, - transport=httpx2.HTTPTransport(uds=str(uds)), + transport=make_uds_transport(str(uds)), ) return HTTPClient( - base_url=f"http://{hostname}:{port}", timeout=REQUEST_TIMEOUT, follow_redirects=True + base_url=f"http://{hostname}:{port}", + timeout=REQUEST_TIMEOUT, + follow_redirects=True, + verify=False, # plain HTTP, no need to build an SSL context ) diff --git a/src/dstack/_internal/utils/http.py b/src/dstack/_internal/utils/http.py index 713cde482..57bd1bbbd 100644 --- a/src/dstack/_internal/utils/http.py +++ b/src/dstack/_internal/utils/http.py @@ -74,6 +74,19 @@ def __init__( ) +def make_uds_transport(path: str) -> httpx2.HTTPTransport: + """ + Returns a transport for plain HTTP over a Unix socket. It builds no SSL context: with the + default `verify=True`, httpx2 would load the CA certificates for every transport. + """ + return httpx2.HTTPTransport(uds=path, verify=False) + + +def make_async_uds_transport(path: str) -> httpx2.AsyncHTTPTransport: + """The async version of `make_uds_transport()`.""" + return httpx2.AsyncHTTPTransport(uds=path, verify=False) + + def _get_headers(headers: Optional[Mapping[str, str]]) -> httpx2.Headers: result = httpx2.Headers({"User-Agent": USER_AGENT}) if headers is not None: diff --git a/src/dstack/api/server/__init__.py b/src/dstack/api/server/__init__.py index c5dced76d..1adfd239e 100644 --- a/src/dstack/api/server/__init__.py +++ b/src/dstack/api/server/__init__.py @@ -15,7 +15,7 @@ ServerClientError, URLNotFoundError, ) -from dstack._internal.utils.http import HTTPClient +from dstack._internal.utils.http import HTTPClient, make_uds_transport from dstack._internal.utils.logging import get_logger from dstack.api.server._auth import AuthAPIClient from dstack.api.server._backends import BackendsAPIClient @@ -82,7 +82,7 @@ def __init__(self, base_url: str, token: Optional[str] = None): headers=headers, timeout=_TIMEOUT, follow_redirects=True, - transport=httpx2.HTTPTransport(uds=socket_path) if socket_path is not None else None, + transport=make_uds_transport(socket_path) if socket_path is not None else None, ) self._logger = get_logger(__name__) diff --git a/src/tests/_internal/utils/test_http.py b/src/tests/_internal/utils/test_http.py index 6e70c51d0..445dc4475 100644 --- a/src/tests/_internal/utils/test_http.py +++ b/src/tests/_internal/utils/test_http.py @@ -67,3 +67,12 @@ def _fail() -> ssl.SSLContext: def _get_ssl_context(client: Union[httpx2.Client, httpx2.AsyncClient]) -> ssl.SSLContext: return client._transport._pool._ssl_context # type: ignore[attr-defined] + + +class TestMakeUDSTransport: + def test_does_not_load_ca_certificates(self): + sync_ctx = http.make_uds_transport("/tmp/test.sock")._pool._ssl_context # type: ignore[attr-defined] + async_ctx = http.make_async_uds_transport("/tmp/test.sock")._pool._ssl_context # type: ignore[attr-defined] + for ctx in (sync_ctx, async_ctx): + assert ctx.verify_mode == ssl.CERT_NONE + assert ctx.cert_store_stats()["x509_ca"] == 0 From c84fe5a4efbb9416d48a22d70b61707370765aef Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:07:50 +0500 Subject: [PATCH 13/37] Raise ClientError for unexpected 400 and 422 response bodies --- src/dstack/api/server/__init__.py | 36 ++++++++++++++++++------ src/tests/api/server/test_api_client.py | 37 ++++++++++++++++++++++++- 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/src/dstack/api/server/__init__.py b/src/dstack/api/server/__init__.py index 1adfd239e..e0d300e14 100644 --- a/src/dstack/api/server/__init__.py +++ b/src/dstack/api/server/__init__.py @@ -4,7 +4,7 @@ import ssl import time import urllib.parse -from typing import Dict, List, Optional, Tuple, Type, Union +from typing import Dict, Optional, Tuple, Type, Union import httpx2 @@ -222,14 +222,15 @@ def _request( ) if raise_for_status: - if resp.status_code == 400: # raise ServerClientError - detail: List[Dict] = resp.json()["detail"] - if len(detail) == 1 and detail[0]["code"] in _server_client_errors: - kwargs = detail[0] - code = kwargs.pop("code") - raise _server_client_errors[code](**kwargs) + if resp.status_code == 400: + error = _get_server_client_error(resp) + if error is not None: + raise error if resp.status_code == 422: - formatted_error = pprint.pformat(resp.json()) + try: + formatted_error = pprint.pformat(resp.json()) + except ValueError: + formatted_error = resp.text raise ClientError(f"Server validation error: \n{formatted_error}") if resp.status_code == 403: raise ClientError( @@ -254,6 +255,25 @@ def _request( _server_client_errors[ServerClientError.code] = ServerClientError +def _get_server_client_error(resp: httpx2.Response) -> Optional[ServerClientError]: + """ + Returns the error from a 400 response in the server's `{"detail": [{"code": ...}]}` format, + or `None` for other bodies, e.g. from a proxy in front of the server. + """ + try: + body = resp.json() + except ValueError: + return None + detail = body.get("detail") if isinstance(body, dict) else None + if not isinstance(detail, list) or len(detail) != 1 or not isinstance(detail[0], dict): + return None + kwargs = dict(detail[0]) + error_cls = _server_client_errors.get(kwargs.pop("code", None)) + if error_cls is None: + return None + return error_cls(**kwargs) + + def _parse_base_url(base_url: str) -> Tuple[str, Optional[str]]: """ Returns the URL to send requests to and, for `http+unix://[/]` diff --git a/src/tests/api/server/test_api_client.py b/src/tests/api/server/test_api_client.py index b0f658a08..96850c837 100644 --- a/src/tests/api/server/test_api_client.py +++ b/src/tests/api/server/test_api_client.py @@ -1,7 +1,7 @@ import httpx2 import pytest -from dstack._internal.core.errors import ClientError, URLNotFoundError +from dstack._internal.core.errors import ClientError, ResourceNotExistsError, URLNotFoundError from dstack.api import server as server_module from dstack.api.server import APIClient from tests.http_mock import HTTPMock @@ -95,6 +95,41 @@ def test_raises_client_error_for_url_without_scheme(self): with pytest.raises(ClientError, match="UnsupportedProtocol"): client._request("/api/users/get_my_user") + @pytest.mark.parametrize( + "response", + [ + {"text": "400 Bad Request"}, + {"json": {"detail": "Bad request"}}, + {"json": {"detail": [{"code": "unknown_code", "msg": "x"}]}}, + ], + ) + def test_raises_client_error_for_unexpected_400_bodies( + self, http_mock: HTTPMock, response: dict + ): + http_mock.post("https://server.test/api/users/get_my_user", status_code=400, **response) + client = APIClient("https://server.test") + + with pytest.raises(ClientError, match="status code 400"): + client._request("/api/users/get_my_user") + + def test_raises_server_client_error_for_400_with_error_code(self, http_mock: HTTPMock): + http_mock.post( + "https://server.test/api/users/get_my_user", + status_code=400, + json={"detail": [{"code": "resource_not_exists", "msg": "Run not found"}]}, + ) + client = APIClient("https://server.test") + + with pytest.raises(ResourceNotExistsError, match="Run not found"): + client._request("/api/users/get_my_user") + + def test_raises_client_error_for_non_json_422(self, http_mock: HTTPMock): + http_mock.post("https://server.test/api/users/get_my_user", status_code=422, text="bad") + client = APIClient("https://server.test") + + with pytest.raises(ClientError, match="Server validation error: \nbad"): + client._request("/api/users/get_my_user") + def test_maps_error_statuses(self, http_mock: HTTPMock): http_mock.post("https://server.test/api/missing", status_code=404) client = APIClient("https://server.test") From 9c154c71a73c7c967c3f751f7138e143375e83c6 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:09:43 +0500 Subject: [PATCH 14/37] Fix optional SSL context typing in test_http --- src/tests/_internal/utils/test_http.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/tests/_internal/utils/test_http.py b/src/tests/_internal/utils/test_http.py index 445dc4475..55ee965cf 100644 --- a/src/tests/_internal/utils/test_http.py +++ b/src/tests/_internal/utils/test_http.py @@ -74,5 +74,6 @@ def test_does_not_load_ca_certificates(self): sync_ctx = http.make_uds_transport("/tmp/test.sock")._pool._ssl_context # type: ignore[attr-defined] async_ctx = http.make_async_uds_transport("/tmp/test.sock")._pool._ssl_context # type: ignore[attr-defined] for ctx in (sync_ctx, async_ctx): + assert ctx is not None assert ctx.verify_mode == ssl.CERT_NONE assert ctx.cert_store_stats()["x509_ca"] == 0 From 9b3b3e0fd814d164e0f5d1f5f99b10a8d8464728 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:12:23 +0500 Subject: [PATCH 15/37] Raise a resolve error for any request error in resolve_url --- src/dstack/_internal/cli/utils/common.py | 2 +- src/tests/_internal/cli/utils/test_common.py | 29 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/dstack/_internal/cli/utils/common.py b/src/dstack/_internal/cli/utils/common.py index b89c51706..e4e2cbf45 100644 --- a/src/dstack/_internal/cli/utils/common.py +++ b/src/dstack/_internal/cli/utils/common.py @@ -176,7 +176,7 @@ def resolve_url(url: str, timeout: float = 5.0) -> str: try: with HTTPClient(timeout=timeout, follow_redirects=True) as client: response = client.get(url) - except (httpx2.ConnectError, httpx2.ConnectTimeout) as e: + except httpx2.HTTPError as e: raise ValueError(f"Failed to resolve url {url}") from e return str(response.url) diff --git a/src/tests/_internal/cli/utils/test_common.py b/src/tests/_internal/cli/utils/test_common.py index 30b15b0cb..ed05a5775 100644 --- a/src/tests/_internal/cli/utils/test_common.py +++ b/src/tests/_internal/cli/utils/test_common.py @@ -8,6 +8,7 @@ from typing import Generator from unittest.mock import patch +import httpx2 import pytest from rich.console import Console from rich.live import Live @@ -17,8 +18,10 @@ _get_cli_log_file, configure_logging, error_console, + resolve_url, warn, ) +from tests.http_mock import HTTPMock @pytest.fixture @@ -174,3 +177,29 @@ def test_has_no_fileno_during_live_display(self): with Live("Working...", console=live_console, auto_refresh=False): with pytest.raises(io.UnsupportedOperation): error_console.file.fileno() + + +class TestResolveURL: + def test_returns_url_after_redirects(self, http_mock: HTTPMock): + http_mock.get( + "http://server.test/", + status_code=301, + headers={"Location": "https://server.test/"}, + ) + http_mock.get("https://server.test/", text="ok") + + assert resolve_url("server.test") == "https://server.test/" + + @pytest.mark.parametrize( + "exc", + [ + httpx2.ConnectError("refused"), + httpx2.ReadTimeout("slow"), + httpx2.RemoteProtocolError("disconnected"), + ], + ) + def test_raises_value_error_on_request_errors(self, http_mock: HTTPMock, exc: Exception): + http_mock.get("http://server.test/", exc=exc) + + with pytest.raises(ValueError, match="Failed to resolve url http://server.test"): + resolve_url("server.test") From cb04a1378708b26b0d820db7945651b190c6df85 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:19:35 +0500 Subject: [PATCH 16/37] Treat non-UTF-8 CloudRift responses as non-JSON --- .../_internal/core/backends/cloudrift/api_client.py | 3 +-- .../core/backends/cloudrift/test_api_client.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/dstack/_internal/core/backends/cloudrift/api_client.py b/src/dstack/_internal/core/backends/cloudrift/api_client.py index d422cde26..4a8c76b78 100644 --- a/src/dstack/_internal/core/backends/cloudrift/api_client.py +++ b/src/dstack/_internal/core/backends/cloudrift/api_client.py @@ -1,4 +1,3 @@ -import json import os import re from typing import Any, Dict, List, Mapping, Optional, Union @@ -220,7 +219,7 @@ def _make_request( response_json["version"], ) return response_json["data"] - except json.JSONDecodeError: + except ValueError: # JSONDecodeError or UnicodeDecodeError return response except httpx2.HTTPStatusError as e: if e.response.status_code in ( diff --git a/src/tests/_internal/core/backends/cloudrift/test_api_client.py b/src/tests/_internal/core/backends/cloudrift/test_api_client.py index 5899e06a5..1881b07c0 100644 --- a/src/tests/_internal/core/backends/cloudrift/test_api_client.py +++ b/src/tests/_internal/core/backends/cloudrift/test_api_client.py @@ -66,6 +66,17 @@ def test_rejects_invalid_credentials(self, http_mock, status_code): with pytest.raises(BackendInvalidCredentialsError, match="invalid key"): RiftClient("test-key")._make_request("auth/me") + @pytest.mark.parametrize( + "content", [b"not json", "caf\xe9".encode("latin-1")], ids=["text", "latin-1"] + ) + def test_returns_non_json_response(self, http_mock, content): + http_mock.post(f"{API_ROOT}/auth/me", content=content) + + response = RiftClient("key")._make_request("auth/me") + + assert isinstance(response, httpx2.Response) + assert response.content == content + def test_preserves_http_errors(self, http_mock): http_mock.post(f"{API_ROOT}/recipes/list", status_code=400, text="unsupported version") From 147674c7b94751d280210ccc895a462ace34d93c Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:20:09 +0500 Subject: [PATCH 17/37] Close gateway connections that fail to open --- .../server/services/gateways/pool.py | 8 ++++- .../server/services/gateways/test_pool.py | 34 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/tests/_internal/server/services/gateways/test_pool.py diff --git a/src/dstack/_internal/server/services/gateways/pool.py b/src/dstack/_internal/server/services/gateways/pool.py index eaed7c2e9..07922a984 100644 --- a/src/dstack/_internal/server/services/gateways/pool.py +++ b/src/dstack/_internal/server/services/gateways/pool.py @@ -32,7 +32,13 @@ async def get_or_add( return self._connections[hostname] except Exception: async with self._lock: - self._connections.pop(hostname, None) + connection = self._connections.pop(hostname, None) + if connection is not None: + # Opening may have failed after starting the SSH tunnel. + try: + await connection.close() + except Exception: + logger.exception("Failed to close the gateway connection to %s", hostname) raise async def remove(self, hostname: str) -> bool: diff --git a/src/tests/_internal/server/services/gateways/test_pool.py b/src/tests/_internal/server/services/gateways/test_pool.py new file mode 100644 index 000000000..c15e86ab9 --- /dev/null +++ b/src/tests/_internal/server/services/gateways/test_pool.py @@ -0,0 +1,34 @@ +from unittest.mock import AsyncMock + +import pytest + +from dstack._internal.server.services.gateways import pool as pool_module +from dstack._internal.server.services.gateways.pool import GatewayConnectionsPool + + +class TestGatewayConnectionsPoolGetOrAdd: + @pytest.mark.asyncio + async def test_closes_and_forgets_connection_that_failed_to_open( + self, monkeypatch: pytest.MonkeyPatch + ): + connection = AsyncMock() + connection.open.side_effect = RuntimeError("ssh failed") + monkeypatch.setattr(pool_module, "GatewayConnection", lambda *args: connection) + pool = GatewayConnectionsPool() + + with pytest.raises(RuntimeError, match="ssh failed"): + await pool.get_or_add("gateway.test", "key") + + connection.close.assert_awaited_once() + assert await pool.all() == [] + + @pytest.mark.asyncio + async def test_raises_open_error_if_close_fails(self, monkeypatch: pytest.MonkeyPatch): + connection = AsyncMock() + connection.open.side_effect = RuntimeError("ssh failed") + connection.close.side_effect = OSError("close failed") + monkeypatch.setattr(pool_module, "GatewayConnection", lambda *args: connection) + pool = GatewayConnectionsPool() + + with pytest.raises(RuntimeError, match="ssh failed"): + await pool.get_or_add("gateway.test", "key") From f1c537ba6dc5ed423729e736b024f1188d4a234a Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:20:55 +0500 Subject: [PATCH 18/37] Report unexpected registry manifests as DockerRegistryError --- src/dstack/_internal/server/services/docker.py | 3 +++ .../_internal/server/services/test_docker.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/dstack/_internal/server/services/docker.py b/src/dstack/_internal/server/services/docker.py index b29e8c843..ff1641b6a 100644 --- a/src/dstack/_internal/server/services/docker.py +++ b/src/dstack/_internal/server/services/docker.py @@ -136,6 +136,9 @@ def get_image_config_and_cpu_architectures( except (DXFError, requests.RequestException, ValidationError) as e: raise DockerRegistryError(e) + except (ValueError, KeyError) as e: + # E.g. a non-JSON manifest or a manifest without the fields DXF expects + raise DockerRegistryError(f"Unexpected image manifest from the registry: {e!r}") from e def apply_server_docker_defaults( diff --git a/src/tests/_internal/server/services/test_docker.py b/src/tests/_internal/server/services/test_docker.py index 2f80a66fb..c41e551fc 100644 --- a/src/tests/_internal/server/services/test_docker.py +++ b/src/tests/_internal/server/services/test_docker.py @@ -396,3 +396,18 @@ def test_rejects_single_platform_image_with_unsupported_platform( with pytest.raises(DockerRegistryError, match="No supported OS/architectures found"): self._get_image_config(_image_manifest("sha256:config"), sample_image_config_object) + + @pytest.mark.parametrize( + "error", + [json.JSONDecodeError("Expecting value", "", 0), KeyError("mediaType")], + ids=["non-json", "missing-field"], + ) + def test_reports_unexpected_manifests_as_registry_errors(self, error: Exception): + registry_client = MagicMock() + registry_client.__enter__.return_value = registry_client + registry_client.get_manifest.side_effect = error + with ( + patch.object(docker_services, "DXF", return_value=registry_client), + pytest.raises(DockerRegistryError, match="Unexpected image manifest"), + ): + get_image_config_and_cpu_architectures("debian", None) From ac1b3838492ea4293d81c17e01c7bc9622585f71 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:21:35 +0500 Subject: [PATCH 19/37] Report only rejected Vast.ai keys as invalid credentials --- .../core/backends/vastai/api_client.py | 13 +++++---- .../core/backends/vastai/test_api_client.py | 28 +++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 src/tests/_internal/core/backends/vastai/test_api_client.py diff --git a/src/dstack/_internal/core/backends/vastai/api_client.py b/src/dstack/_internal/core/backends/vastai/api_client.py index bab0eaf07..3dbd41838 100644 --- a/src/dstack/_internal/core/backends/vastai/api_client.py +++ b/src/dstack/_internal/core/backends/vastai/api_client.py @@ -1,8 +1,6 @@ import json from typing import Optional, Union -import httpx2 - import dstack._internal.utils.docker as docker from dstack._internal.core.consts import DSTACK_RUNNER_SSH_PORT from dstack._internal.core.errors import ComputeError @@ -122,8 +120,11 @@ def get_instance(self, instance_id: Union[str, int]) -> Optional[dict]: return data["instances"] def auth_test(self) -> bool: - try: - self.s.get("/v1/instances/").raise_for_status() - return True - except httpx2.HTTPError: + """ + Returns `False` if the API key is rejected. Raises on other errors, e.g. network errors. + """ + resp = self.s.get("/v1/instances/") + if resp.status_code in (401, 403): return False + resp.raise_for_status() + return True diff --git a/src/tests/_internal/core/backends/vastai/test_api_client.py b/src/tests/_internal/core/backends/vastai/test_api_client.py new file mode 100644 index 000000000..80268b498 --- /dev/null +++ b/src/tests/_internal/core/backends/vastai/test_api_client.py @@ -0,0 +1,28 @@ +import httpx2 +import pytest + +from dstack._internal.core.backends.vastai.api_client import VastAIAPIClient +from tests.http_mock import HTTPMock + +INSTANCES_URL = "https://console.vast.ai/api/v1/instances/" + + +class TestVastAIAPIClientAuthTest: + def test_accepts_valid_key(self, http_mock: HTTPMock): + http_mock.get(INSTANCES_URL, json={"instances": []}) + assert VastAIAPIClient("key").auth_test() + + @pytest.mark.parametrize("status_code", [401, 403]) + def test_rejects_invalid_key(self, http_mock: HTTPMock, status_code: int): + http_mock.get(INSTANCES_URL, status_code=status_code) + assert not VastAIAPIClient("key").auth_test() + + @pytest.mark.parametrize( + "response", + [{"status_code": 503}, {"exc": httpx2.ConnectError("refused")}], + ids=["server-error", "network-error"], + ) + def test_raises_on_other_errors(self, http_mock: HTTPMock, response: dict): + http_mock.get(INSTANCES_URL, **response) + with pytest.raises(httpx2.HTTPError): + VastAIAPIClient("key").auth_test() From 9012ecfc1278c580c3a17e20a358693d9b52b809 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:22:48 +0500 Subject: [PATCH 20/37] Close evicted gateway server clients --- .../proxy/gateway/services/server_client.py | 42 ++++++++++--------- .../gateway/services/test_server_client.py | 22 +++++++++- 2 files changed, 42 insertions(+), 22 deletions(-) diff --git a/src/dstack/_internal/proxy/gateway/services/server_client.py b/src/dstack/_internal/proxy/gateway/services/server_client.py index cc8f8c94f..8e3fd03d6 100644 --- a/src/dstack/_internal/proxy/gateway/services/server_client.py +++ b/src/dstack/_internal/proxy/gateway/services/server_client.py @@ -3,7 +3,7 @@ import random from dataclasses import dataclass, field from pathlib import Path -from typing import Container, Dict, Generator, List +from typing import Container, Dict, List import httpx2 @@ -45,10 +45,14 @@ def __init__(self, sockets_dir: Path): async def send(self, request: httpx2.Request, *args, **kwargs) -> httpx2.Response: errors: List[httpx2.RequestError] = [] - clients_count = 0 + sockets = list(self._sockets_dir.glob("*.sock")) + await self._evict_clients(stems_to_keep={s.stem for s in sockets}) + # Each socket forwards to a server replica; shuffle to distribute auth checks. + random.shuffle(sockets) # Try another replica after request errors; HTTP error responses are returned. - for clients_count, client in enumerate(self._iter_clients_rand(), start=1): + for socket in sockets: + client = self._get_client(socket) try: resp = await client.client.send(request, *args, **kwargs) client.connect_errors = [] @@ -66,26 +70,23 @@ async def send(self, request: httpx2.Request, *args, **kwargs) -> httpx2.Respons logger.warning("Request failed with socket %s: %r", client.socket, e) msg = f"Cannot request {request.url.path}: " - if not clients_count: + if not sockets: msg += f"no sockets found in {self._sockets_dir}" elif not errors: - msg += f"all {clients_count} socket(s) in {self._sockets_dir} are disconnected" + msg += f"all {len(sockets)} socket(s) in {self._sockets_dir} are disconnected" else: msg += f"{len(errors)} socket(s) failed. Last error: {errors[-1]!r}" raise httpx2.RequestError(msg, request=request) - def _iter_clients_rand(self) -> Generator[CachedClientInfo, None, None]: - sockets = list(self._sockets_dir.glob("*.sock")) - self._evict_clients(stems_to_keep={s.stem for s in sockets}) - # Each socket forwards to a server replica; shuffle to distribute auth checks. - random.shuffle(sockets) + async def aclose(self) -> None: + await self._evict_clients(stems_to_keep=()) + await super().aclose() - for socket in sockets: - if socket.stem in self._clients_cache: - cached_client = self._clients_cache[socket.stem] - else: - cached_client = self._clients_cache[socket.stem] = self._make_client(socket) - yield cached_client + def _get_client(self, socket: Path) -> CachedClientInfo: + client = self._clients_cache.get(socket.stem) + if client is None: + client = self._clients_cache[socket.stem] = self._make_client(socket) + return client @staticmethod def _make_client(socket: Path) -> CachedClientInfo: @@ -100,7 +101,8 @@ def _make_client(socket: Path) -> CachedClientInfo: socket=socket, ) - def _evict_clients(self, stems_to_keep: Container[str]) -> None: - self._clients_cache = { - stem: client for stem, client in self._clients_cache.items() if stem in stems_to_keep - } + async def _evict_clients(self, stems_to_keep: Container[str]) -> None: + evicted = [stem for stem in self._clients_cache if stem not in stems_to_keep] + for stem in evicted: + # The socket is gone, so requests in flight through this client fail anyway. + await self._clients_cache.pop(stem).client.aclose() diff --git a/src/tests/_internal/proxy/gateway/services/test_server_client.py b/src/tests/_internal/proxy/gateway/services/test_server_client.py index 9c335b8f0..a4a2a0fec 100644 --- a/src/tests/_internal/proxy/gateway/services/test_server_client.py +++ b/src/tests/_internal/proxy/gateway/services/test_server_client.py @@ -19,7 +19,7 @@ class TestHTTPMultiClient: async def test_recovers_after_cancelled_pool_waiter(self, tmp_path, monkeypatch, failure): (tmp_path / "server.sock").touch() client = HTTPMultiClient(tmp_path) - cached = next(client._iter_clients_rand()) + cached = client._get_client(tmp_path / "server.sock") pool = cast(httpx2.AsyncHTTPTransport, cached.client._transport)._pool assert isinstance(pool, httpcore.AsyncConnectionPool) pool._max_connections = 1 @@ -75,7 +75,7 @@ async def test_failover_preserves_http_responses(self, tmp_path, monkeypatch, ou (tmp_path / name).touch() monkeypatch.setattr("random.shuffle", lambda sockets: sockets.sort()) client = HTTPMultiClient(tmp_path) - cached = list(client._iter_clients_rand()) + cached = [client._get_client(tmp_path / name) for name in ("a.sock", "b.sock")] requests = [] def first(request): @@ -133,3 +133,21 @@ async def handle(reader, writer): await client.aclose() server.close() await server.wait_closed() + + +class TestHTTPMultiClientEviction: + @pytest.mark.asyncio + async def test_closes_clients_of_removed_sockets(self, tmp_path): + for name in ("a.sock", "b.sock"): + (tmp_path / name).touch() + client = HTTPMultiClient(tmp_path) + kept = client._get_client(tmp_path / "a.sock") + removed = client._get_client(tmp_path / "b.sock") + (tmp_path / "b.sock").unlink() + + await client._evict_clients(stems_to_keep={"a"}) + + assert removed.client.is_closed + assert not kept.client.is_closed + await client.aclose() + assert kept.client.is_closed From 67728c82c1b64c893f7e273de3f2d343c07270f1 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:23:57 +0500 Subject: [PATCH 21/37] Add close() to APIClient and Client --- src/dstack/api/_public/__init__.py | 14 +++++++++++++- src/dstack/api/server/__init__.py | 14 +++++++++++++- src/tests/api/server/test_api_client.py | 12 ++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/dstack/api/_public/__init__.py b/src/dstack/api/_public/__init__.py index 1d9ab353d..462f62338 100644 --- a/src/dstack/api/_public/__init__.py +++ b/src/dstack/api/_public/__init__.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Optional, Self import dstack._internal.core.services.api_client as api_client_service from dstack._internal.core.errors import ConfigurationError @@ -94,3 +94,15 @@ def backends(self) -> BackendCollection: @property def client(self) -> APIClient: return self._client + + def close(self) -> None: + """ + Closes the connections to the server. The client must not be used after that. + """ + self._client.close() + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: object) -> None: + self.close() diff --git a/src/dstack/api/server/__init__.py b/src/dstack/api/server/__init__.py index e0d300e14..182bdf5b6 100644 --- a/src/dstack/api/server/__init__.py +++ b/src/dstack/api/server/__init__.py @@ -4,7 +4,7 @@ import ssl import time import urllib.parse -from typing import Dict, Optional, Tuple, Type, Union +from typing import Dict, Optional, Self, Tuple, Type, Union import httpx2 @@ -166,6 +166,18 @@ def events(self) -> EventsAPIClient: def token(self) -> Optional[str]: return self._token + def close(self) -> None: + """ + Closes the connections to the server. The client must not be used after that. + """ + self._client.close() + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: object) -> None: + self.close() + def get_token_hash(self) -> str: if self._token is None: raise ValueError("Token not set") diff --git a/src/tests/api/server/test_api_client.py b/src/tests/api/server/test_api_client.py index 96850c837..0f9405080 100644 --- a/src/tests/api/server/test_api_client.py +++ b/src/tests/api/server/test_api_client.py @@ -152,3 +152,15 @@ class TestParseBaseURL: ) def test_parses(self, base_url: str, expected: tuple): assert server_module._parse_base_url(base_url) == expected + + +class TestAPIClientClose: + def test_closes_connections(self): + client = APIClient("https://server.test") + client.close() + assert client._client.is_closed + + def test_closes_on_exiting_context(self): + with APIClient("https://server.test") as client: + pass + assert client._client.is_closed From c43d55bdf339f4679799df6e48e2851301a89c70 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:24:55 +0500 Subject: [PATCH 22/37] Fix concurrent eviction of gateway server clients --- .../proxy/gateway/services/server_client.py | 11 ++++++--- .../gateway/services/test_server_client.py | 24 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/dstack/_internal/proxy/gateway/services/server_client.py b/src/dstack/_internal/proxy/gateway/services/server_client.py index 8e3fd03d6..6a05bdd16 100644 --- a/src/dstack/_internal/proxy/gateway/services/server_client.py +++ b/src/dstack/_internal/proxy/gateway/services/server_client.py @@ -102,7 +102,12 @@ def _make_client(socket: Path) -> CachedClientInfo: ) async def _evict_clients(self, stems_to_keep: Container[str]) -> None: - evicted = [stem for stem in self._clients_cache if stem not in stems_to_keep] - for stem in evicted: + # Remove all evicted clients before awaiting, so that concurrent calls don't race. + evicted = [ + self._clients_cache.pop(stem) + for stem in list(self._clients_cache) + if stem not in stems_to_keep + ] + for info in evicted: # The socket is gone, so requests in flight through this client fail anyway. - await self._clients_cache.pop(stem).client.aclose() + await info.client.aclose() diff --git a/src/tests/_internal/proxy/gateway/services/test_server_client.py b/src/tests/_internal/proxy/gateway/services/test_server_client.py index a4a2a0fec..f085d3f05 100644 --- a/src/tests/_internal/proxy/gateway/services/test_server_client.py +++ b/src/tests/_internal/proxy/gateway/services/test_server_client.py @@ -151,3 +151,27 @@ async def test_closes_clients_of_removed_sockets(self, tmp_path): assert not kept.client.is_closed await client.aclose() assert kept.client.is_closed + + @pytest.mark.asyncio + async def test_concurrent_evictions_do_not_conflict(self, tmp_path, monkeypatch): + client = HTTPMultiClient(tmp_path) + for name in ("a.sock", "b.sock"): + info = client._get_client(tmp_path / name) + monkeypatch.setattr(info.client, "aclose", _yielding_aclose(info.client.aclose)) + + await asyncio.gather( + client._evict_clients(stems_to_keep=()), + client._evict_clients(stems_to_keep=()), + ) + + assert client._clients_cache == {} + await client.aclose() + + +def _yielding_aclose(aclose): + async def wrapper() -> None: + # Closing open connections suspends, letting other coroutines run in between. + await asyncio.sleep(0) + await aclose() + + return wrapper From d58eb2d1708280ad4881d167681a138cc3a0312e Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:41:23 +0500 Subject: [PATCH 23/37] Keep replacement gateway connection when a failed open cleans up --- .../server/services/gateways/pool.py | 24 +++++++++---------- .../server/services/gateways/test_pool.py | 23 ++++++++++++++++++ 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/src/dstack/_internal/server/services/gateways/pool.py b/src/dstack/_internal/server/services/gateways/pool.py index 07922a984..21fcea5ea 100644 --- a/src/dstack/_internal/server/services/gateways/pool.py +++ b/src/dstack/_internal/server/services/gateways/pool.py @@ -23,22 +23,22 @@ async def get_or_add( connection = self._connections.get(hostname) if connection is not None: return connection - self._connections[hostname] = GatewayConnection(hostname, id_rsa, SERVER_PORT) - open_task = self._connections[hostname].open( - close_existing_tunnel=close_existing_tunnel, - ) + connection = GatewayConnection(hostname, id_rsa, SERVER_PORT) + self._connections[hostname] = connection + open_task = connection.open(close_existing_tunnel=close_existing_tunnel) try: await open_task - return self._connections[hostname] + return connection except Exception: async with self._lock: - connection = self._connections.pop(hostname, None) - if connection is not None: - # Opening may have failed after starting the SSH tunnel. - try: - await connection.close() - except Exception: - logger.exception("Failed to close the gateway connection to %s", hostname) + # The connection may have been removed and replaced while opening. + if self._connections.get(hostname) is connection: + del self._connections[hostname] + # Opening may have failed after starting the SSH tunnel. + try: + await connection.close() + except Exception: + logger.exception("Failed to close the gateway connection to %s", hostname) raise async def remove(self, hostname: str) -> bool: diff --git a/src/tests/_internal/server/services/gateways/test_pool.py b/src/tests/_internal/server/services/gateways/test_pool.py index c15e86ab9..297610e6c 100644 --- a/src/tests/_internal/server/services/gateways/test_pool.py +++ b/src/tests/_internal/server/services/gateways/test_pool.py @@ -32,3 +32,26 @@ async def test_raises_open_error_if_close_fails(self, monkeypatch: pytest.Monkey with pytest.raises(RuntimeError, match="ssh failed"): await pool.get_or_add("gateway.test", "key") + + @pytest.mark.asyncio + async def test_failed_open_keeps_connection_that_replaced_it( + self, monkeypatch: pytest.MonkeyPatch + ): + pool = GatewayConnectionsPool() + failed = AsyncMock() + replacement = AsyncMock() + connections = iter([failed, replacement]) + monkeypatch.setattr(pool_module, "GatewayConnection", lambda *args: next(connections)) + + async def remove_and_replace(**kwargs): + await pool.remove("gateway.test") + await pool.get_or_add("gateway.test", "key") + raise RuntimeError("ssh failed") + + failed.open.side_effect = remove_and_replace + + with pytest.raises(RuntimeError, match="ssh failed"): + await pool.get_or_add("gateway.test", "key") + + replacement.close.assert_not_awaited() + assert await pool.all() == [replacement] From 0d8c2554ba87c627cb8ac17ee18667e061368205 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:41:24 +0500 Subject: [PATCH 24/37] Raise GatewayError when using a closed gateway connection --- .../server/services/gateways/connection.py | 7 +++++++ .../server/services/gateways/test_connection.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/dstack/_internal/server/services/gateways/connection.py b/src/dstack/_internal/server/services/gateways/connection.py index cd502b5d0..650c01b2d 100644 --- a/src/dstack/_internal/server/services/gateways/connection.py +++ b/src/dstack/_internal/server/services/gateways/connection.py @@ -6,6 +6,7 @@ import aiorwlock +from dstack._internal.core.errors import GatewayError from dstack._internal.core.services.ssh.tunnel import ( SSH_DEFAULT_OPTIONS, IPSocket, @@ -72,6 +73,7 @@ def __init__(self, ip_address: str, id_rsa: str, server_port: int): ) self.tunnel_id = uuid.uuid4() self._client = GatewayClient(uds=str(self.gateway_socket_path)) + self._closed = False async def check_or_restart(self) -> bool: async with self._lock.writer_lock: @@ -110,6 +112,7 @@ async def _open_tunnel(self) -> None: async def close(self) -> None: async with self._lock.writer_lock: + self._closed = True await self._client.aclose() await self.tunnel.aclose() shutil.rmtree(self.connection_dir, ignore_errors=True) @@ -119,6 +122,8 @@ async def try_collect_stats(self) -> None: return async with self._lock.writer_lock: + if self._closed: + return stats = {} for service in await self._client.collect_stats(): logger.debug( @@ -134,4 +139,6 @@ async def get_stats(self, project_name: str, run_name: str) -> Optional[PerWindo @contextlib.asynccontextmanager async def client(self) -> AsyncIterator[GatewayClient]: async with self._lock.reader_lock: + if self._closed: + raise GatewayError(f"Connection to gateway {self.ip_address} is closed") yield self._client diff --git a/src/tests/_internal/server/services/gateways/test_connection.py b/src/tests/_internal/server/services/gateways/test_connection.py index 66070d9a8..295c4eac4 100644 --- a/src/tests/_internal/server/services/gateways/test_connection.py +++ b/src/tests/_internal/server/services/gateways/test_connection.py @@ -3,6 +3,7 @@ import pytest +from dstack._internal.core.errors import GatewayError from dstack._internal.server import settings from dstack._internal.server.services.gateways.connection import GatewayConnection @@ -22,3 +23,17 @@ async def test_close_closes_client_and_tunnel( assert conn._client._client.is_closed tunnel_aclose.assert_awaited_once() + + @pytest.mark.asyncio + async def test_client_raises_gateway_error_after_close( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ): + monkeypatch.setattr(settings, "SERVER_DIR_PATH", tmp_path) + conn = GatewayConnection(ip_address="10.0.0.1", id_rsa="key", server_port=3000) + monkeypatch.setattr(conn.tunnel, "aclose", AsyncMock()) + + await conn.close() + + with pytest.raises(GatewayError): + async with conn.client(): + pass From 9d08986cba1902827077d8838357dcc233dcdef5 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:41:24 +0500 Subject: [PATCH 25/37] Close evicted gateway server clients only when idle Closing a client under an in-flight request can fail it with an error other than httpx2.RequestError, which bypasses failover to other replicas. --- .../proxy/gateway/services/server_client.py | 16 ++++++++- .../gateway/services/test_server_client.py | 33 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/dstack/_internal/proxy/gateway/services/server_client.py b/src/dstack/_internal/proxy/gateway/services/server_client.py index 6a05bdd16..68efd10c9 100644 --- a/src/dstack/_internal/proxy/gateway/services/server_client.py +++ b/src/dstack/_internal/proxy/gateway/services/server_client.py @@ -21,6 +21,9 @@ class CachedClientInfo: client: httpx2.AsyncClient socket: Path connect_errors: List[datetime.datetime] = field(default_factory=lambda: []) + requests_in_flight: int = 0 + evicted: bool = False + """Set once removed from the cache. The client is closed when no requests are in flight.""" def seems_disconnected(self) -> bool: # Only ConnectError is recorded; a returned HTTP response clears this history. @@ -53,6 +56,7 @@ async def send(self, request: httpx2.Request, *args, **kwargs) -> httpx2.Respons # Try another replica after request errors; HTTP error responses are returned. for socket in sockets: client = self._get_client(socket) + client.requests_in_flight += 1 try: resp = await client.client.send(request, *args, **kwargs) client.connect_errors = [] @@ -68,6 +72,9 @@ async def send(self, request: httpx2.Request, *args, **kwargs) -> httpx2.Respons except httpx2.RequestError as e: errors.append(e) logger.warning("Request failed with socket %s: %r", client.socket, e) + finally: + client.requests_in_flight -= 1 + await self._close_client_if_unused(client) msg = f"Cannot request {request.url.path}: " if not sockets: @@ -109,5 +116,12 @@ async def _evict_clients(self, stems_to_keep: Container[str]) -> None: if stem not in stems_to_keep ] for info in evicted: - # The socket is gone, so requests in flight through this client fail anyway. + info.evicted = True + await self._close_client_if_unused(info) + + @staticmethod + async def _close_client_if_unused(info: CachedClientInfo) -> None: + # Closing a client under an in-flight request can fail that request with an error + # other than httpx2.RequestError, which would bypass failover to other replicas. + if info.evicted and info.requests_in_flight == 0: await info.client.aclose() diff --git a/src/tests/_internal/proxy/gateway/services/test_server_client.py b/src/tests/_internal/proxy/gateway/services/test_server_client.py index f085d3f05..eb5d28cb9 100644 --- a/src/tests/_internal/proxy/gateway/services/test_server_client.py +++ b/src/tests/_internal/proxy/gateway/services/test_server_client.py @@ -167,6 +167,39 @@ async def test_concurrent_evictions_do_not_conflict(self, tmp_path, monkeypatch) assert client._clients_cache == {} await client.aclose() + @pytest.mark.asyncio + async def test_defers_closing_evicted_client_until_request_completes(self, tmp_path): + (tmp_path / "a.sock").touch() + client = HTTPMultiClient(tmp_path) + info = client._get_client(tmp_path / "a.sock") + started = asyncio.Event() + release = asyncio.Event() + + async def handler(request): + started.set() + await release.wait() + return httpx2.Response(200) + + await info.client.aclose() + info.client = httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) + request = asyncio.create_task(client.post("/api/projects/test/get")) + try: + await asyncio.wait_for(started.wait(), timeout=1) + (tmp_path / "a.sock").unlink() + await client._evict_clients(stems_to_keep=()) + assert not info.client.is_closed + + release.set() + response = await request + + assert response.status_code == 200 + assert info.client.is_closed + finally: + release.set() + await asyncio.gather(request, return_exceptions=True) + await info.client.aclose() + await client.aclose() + def _yielding_aclose(aclose): async def wrapper() -> None: From 185f21edb81ed7775fc87a2bf1d8c30721b7368f Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:41:25 +0500 Subject: [PATCH 26/37] Add close() to Vast.ai API client and compute --- src/dstack/_internal/core/backends/vastai/api_client.py | 3 +++ src/dstack/_internal/core/backends/vastai/compute.py | 3 +++ 2 files changed, 6 insertions(+) diff --git a/src/dstack/_internal/core/backends/vastai/api_client.py b/src/dstack/_internal/core/backends/vastai/api_client.py index 3dbd41838..9118cfd66 100644 --- a/src/dstack/_internal/core/backends/vastai/api_client.py +++ b/src/dstack/_internal/core/backends/vastai/api_client.py @@ -37,6 +37,9 @@ def __init__(self, api_key: str): timeout=30, ) + def close(self) -> None: + self.s.close() + def create_instance( self, instance_name: str, diff --git a/src/dstack/_internal/core/backends/vastai/compute.py b/src/dstack/_internal/core/backends/vastai/compute.py index 2563c9208..a7190e126 100644 --- a/src/dstack/_internal/core/backends/vastai/compute.py +++ b/src/dstack/_internal/core/backends/vastai/compute.py @@ -56,6 +56,9 @@ def __init__(self, config: VastAIConfig): self.config = config self.api_client = VastAIAPIClient(config.creds.api_key) + def close(self) -> None: + self.api_client.close() + def _make_catalog(self, options: VastAIProfileOptions) -> gpuhunt.Catalog: filters = { "direct_port_count": {"gte": 1}, From 7c34c661db96da511aa3ed1cc796cb0e29bd1c7c Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:41:26 +0500 Subject: [PATCH 27/37] Close backend API clients created for credentials validation --- .../core/backends/amddevcloud/configurator.py | 9 ++-- .../core/backends/cloudrift/configurator.py | 6 ++- .../core/backends/crusoe/configurator.py | 46 ++++++++++--------- .../core/backends/daytona/configurator.py | 43 ++++++++--------- .../backends/digitalocean/configurator.py | 9 ++-- .../core/backends/hotaisle/configurator.py | 5 +- .../core/backends/jarvislabs/configurator.py | 6 ++- .../core/backends/lambdalabs/configurator.py | 6 ++- .../core/backends/lium/configurator.py | 4 +- .../backends/massedcompute/configurator.py | 5 +- .../core/backends/runpod/configurator.py | 6 ++- .../core/backends/seeweb/configurator.py | 5 +- .../core/backends/vastai/configurator.py | 6 ++- .../core/backends/vultr/configurator.py | 6 ++- 14 files changed, 95 insertions(+), 67 deletions(-) diff --git a/src/dstack/_internal/core/backends/amddevcloud/configurator.py b/src/dstack/_internal/core/backends/amddevcloud/configurator.py index 59fa5654a..7cabfa712 100644 --- a/src/dstack/_internal/core/backends/amddevcloud/configurator.py +++ b/src/dstack/_internal/core/backends/amddevcloud/configurator.py @@ -1,3 +1,4 @@ +from contextlib import closing from typing import Optional from dstack._internal.core.backends.amddevcloud.backend import AMDDevCloudBackend @@ -23,7 +24,7 @@ def get_backend(self, record: BackendRecord) -> BaseDigitalOceanBackend: return AMDDevCloudBackend(config=config, api_url=self.API_URL) def _validate_creds(self, creds: AnyBaseDigitalOceanCreds, project_name: Optional[str] = None): - api_client = DigitalOceanAPIClient(creds.api_key, self.API_URL) - api_client.validate_api_key() - if project_name: - api_client.validate_project_name(project_name) + with closing(DigitalOceanAPIClient(creds.api_key, self.API_URL)) as api_client: + api_client.validate_api_key() + if project_name: + api_client.validate_project_name(project_name) diff --git a/src/dstack/_internal/core/backends/cloudrift/configurator.py b/src/dstack/_internal/core/backends/cloudrift/configurator.py index 82dd1ebc6..4fb4b3bcd 100644 --- a/src/dstack/_internal/core/backends/cloudrift/configurator.py +++ b/src/dstack/_internal/core/backends/cloudrift/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -71,6 +72,7 @@ def _get_config(self, record: BackendRecord) -> CloudRiftConfig: def _validate_creds(self, creds: AnyCloudRiftCreds): if not isinstance(creds, CloudRiftCreds): raise_invalid_credentials_error(fields=[["creds"]]) - client = RiftClient(creds.api_key) - if not client.validate_api_key(): + with closing(RiftClient(creds.api_key)) as client: + is_valid = client.validate_api_key() + if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_key"]]) diff --git a/src/dstack/_internal/core/backends/crusoe/configurator.py b/src/dstack/_internal/core/backends/crusoe/configurator.py index d10f4dc53..8b98ac561 100644 --- a/src/dstack/_internal/core/backends/crusoe/configurator.py +++ b/src/dstack/_internal/core/backends/crusoe/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -28,27 +29,8 @@ class CrusoeConfigurator( BACKEND_CLASS = CrusoeBackend def validate_config(self, config: CrusoeBackendConfigWithCreds, default_creds_enabled: bool): - try: - client = CrusoeClient(config.creds, config.project_id) - client.list_quotas() - except Exception as e: - raise_invalid_credentials_error( - fields=[["creds"]], - details=str(e), - ) - if config.regions: - try: - available = set(client.list_locations()) - except Exception: - return - invalid = set(config.regions) - available - if invalid: - raise_invalid_credentials_error( - fields=[["regions"]], - details=( - f"Unknown regions: {sorted(invalid)}. Valid regions: {sorted(available)}" - ), - ) + with closing(CrusoeClient(config.creds, config.project_id)) as client: + self._validate_config(client, config) def create_backend( self, project_name: str, config: CrusoeBackendConfigWithCreds @@ -80,3 +62,25 @@ def _get_config(self, record: BackendRecord) -> CrusoeConfig: "creds": validate_json_extra_ignore(CrusoeCreds, record.auth), }, ) + + def _validate_config(self, client: CrusoeClient, config: CrusoeBackendConfigWithCreds): + try: + client.list_quotas() + except Exception as e: + raise_invalid_credentials_error( + fields=[["creds"]], + details=str(e), + ) + if config.regions: + try: + available = set(client.list_locations()) + except Exception: + return + invalid = set(config.regions) - available + if invalid: + raise_invalid_credentials_error( + fields=[["regions"]], + details=( + f"Unknown regions: {sorted(invalid)}. Valid regions: {sorted(available)}" + ), + ) diff --git a/src/dstack/_internal/core/backends/daytona/configurator.py b/src/dstack/_internal/core/backends/daytona/configurator.py index 184e51d4a..406af03a7 100644 --- a/src/dstack/_internal/core/backends/daytona/configurator.py +++ b/src/dstack/_internal/core/backends/daytona/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from gpuhunt.providers.daytona import GPU_REGION @@ -22,27 +23,27 @@ class DaytonaConfigurator(Configurator[DaytonaBackendConfig, DaytonaBackendConfi BACKEND_CLASS = DaytonaBackend def validate_config(self, config: DaytonaBackendConfigWithCreds, default_creds_enabled: bool): - client = DaytonaAPIClient(api_key=config.creds.api_key) - api_key = client.get_current_api_key() - required_permissions = {"write:sandboxes", "delete:sandboxes", "read:limits"} - missing_permissions = sorted(required_permissions - set(api_key["permissions"])) - if missing_permissions: - raise BackendInvalidCredentialsError( - msg=f"Daytona API key is missing permissions: {', '.join(missing_permissions)}", - fields=[["creds", "api_key"]], - ) - if not config.regions: - return - regions = {GPU_REGION, *(region["id"] for region in client.get_shared_regions())} - invalid_regions = sorted(set(config.regions) - regions) - if invalid_regions: - raise ServerClientError( - msg=( - f"Unsupported Daytona regions: {invalid_regions}. " - f"Supported regions: {sorted(regions)}." - ), - fields=[["regions"]], - ) + with closing(DaytonaAPIClient(api_key=config.creds.api_key)) as client: + api_key = client.get_current_api_key() + required_permissions = {"write:sandboxes", "delete:sandboxes", "read:limits"} + missing_permissions = sorted(required_permissions - set(api_key["permissions"])) + if missing_permissions: + raise BackendInvalidCredentialsError( + msg=f"Daytona API key is missing permissions: {', '.join(missing_permissions)}", + fields=[["creds", "api_key"]], + ) + if not config.regions: + return + regions = {GPU_REGION, *(region["id"] for region in client.get_shared_regions())} + invalid_regions = sorted(set(config.regions) - regions) + if invalid_regions: + raise ServerClientError( + msg=( + f"Unsupported Daytona regions: {invalid_regions}. " + f"Supported regions: {sorted(regions)}." + ), + fields=[["regions"]], + ) def create_backend( self, project_name: str, config: DaytonaBackendConfigWithCreds diff --git a/src/dstack/_internal/core/backends/digitalocean/configurator.py b/src/dstack/_internal/core/backends/digitalocean/configurator.py index 045372312..38ae4788c 100644 --- a/src/dstack/_internal/core/backends/digitalocean/configurator.py +++ b/src/dstack/_internal/core/backends/digitalocean/configurator.py @@ -1,3 +1,4 @@ +from contextlib import closing from typing import Optional from dstack._internal.core.backends.base.configurator import BackendRecord @@ -25,7 +26,7 @@ def get_backend(self, record: BackendRecord) -> BaseDigitalOceanBackend: return DigitalOceanBackend(config=config, api_url=self.API_URL) def _validate_creds(self, creds: AnyBaseDigitalOceanCreds, project_name: Optional[str] = None): - api_client = DigitalOceanAPIClient(creds.api_key, self.API_URL) - api_client.validate_api_key() - if project_name: - api_client.validate_project_name(project_name) + with closing(DigitalOceanAPIClient(creds.api_key, self.API_URL)) as api_client: + api_client.validate_api_key() + if project_name: + api_client.validate_project_name(project_name) diff --git a/src/dstack/_internal/core/backends/hotaisle/configurator.py b/src/dstack/_internal/core/backends/hotaisle/configurator.py index 6d3ff7a39..3f154587b 100644 --- a/src/dstack/_internal/core/backends/hotaisle/configurator.py +++ b/src/dstack/_internal/core/backends/hotaisle/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -66,5 +67,5 @@ def _get_config(self, record: BackendRecord) -> HotAisleConfig: ) def _validate_creds(self, creds: AnyHotAisleCreds, team_handle: str): - api_client = HotAisleAPIClient(creds.api_key, team_handle) - api_client.validate_api_key() + with closing(HotAisleAPIClient(creds.api_key, team_handle)) as api_client: + api_client.validate_api_key() diff --git a/src/dstack/_internal/core/backends/jarvislabs/configurator.py b/src/dstack/_internal/core/backends/jarvislabs/configurator.py index 1dd358a92..695dd5b73 100644 --- a/src/dstack/_internal/core/backends/jarvislabs/configurator.py +++ b/src/dstack/_internal/core/backends/jarvislabs/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from gpuhunt.providers.jarvislabs import JARVISLABS_REGION_URLS @@ -70,8 +71,9 @@ def _get_config(self, record: BackendRecord) -> JarvisLabsConfig: ) def _validate_api_key(self, api_key: str): - client = api_client.JarvisLabsAPIClient(api_key=api_key) - if not client.validate_api_key(): + with closing(api_client.JarvisLabsAPIClient(api_key=api_key)) as client: + is_valid = client.validate_api_key() + if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_key"]]) def _validate_regions(self, regions: list[str] | None): diff --git a/src/dstack/_internal/core/backends/lambdalabs/configurator.py b/src/dstack/_internal/core/backends/lambdalabs/configurator.py index bcb8ad4f3..8a91fbf2f 100644 --- a/src/dstack/_internal/core/backends/lambdalabs/configurator.py +++ b/src/dstack/_internal/core/backends/lambdalabs/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -64,6 +65,7 @@ def _get_config(self, record: BackendRecord) -> LambdaConfig: ) def _validate_lambda_api_key(self, api_key: str): - client = api_client.LambdaAPIClient(api_key=api_key) - if not client.validate_api_key(): + with closing(api_client.LambdaAPIClient(api_key=api_key)) as client: + is_valid = client.validate_api_key() + if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_key"]]) diff --git a/src/dstack/_internal/core/backends/lium/configurator.py b/src/dstack/_internal/core/backends/lium/configurator.py index 85b27ea44..e27812cdc 100644 --- a/src/dstack/_internal/core/backends/lium/configurator.py +++ b/src/dstack/_internal/core/backends/lium/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import BackendRecord, Configurator from dstack._internal.core.backends.lium.api_client import LiumAPIClient, LiumAPIError @@ -21,7 +22,8 @@ class LiumConfigurator(Configurator[LiumBackendConfig, LiumBackendConfigWithCred def validate_config(self, config: LiumBackendConfigWithCreds, default_creds_enabled: bool): try: - LiumAPIClient(config.creds.api_key).get_user() + with closing(LiumAPIClient(config.creds.api_key)) as client: + client.get_user() except LiumAPIError as e: if e.status_code == 401: raise BackendInvalidCredentialsError(fields=[["creds", "api_key"]]) from e diff --git a/src/dstack/_internal/core/backends/massedcompute/configurator.py b/src/dstack/_internal/core/backends/massedcompute/configurator.py index 2cf76b5e4..6a6fdb763 100644 --- a/src/dstack/_internal/core/backends/massedcompute/configurator.py +++ b/src/dstack/_internal/core/backends/massedcompute/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -27,7 +28,9 @@ class MassedComputeConfigurator( def validate_config( self, config: MassedComputeBackendConfigWithCreds, default_creds_enabled: bool ) -> None: - if not MassedComputeAPIClient(config.creds.api_key).validate_api_key(): + with closing(MassedComputeAPIClient(config.creds.api_key)) as client: + is_valid = client.validate_api_key() + if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_key"]]) def create_backend( diff --git a/src/dstack/_internal/core/backends/runpod/configurator.py b/src/dstack/_internal/core/backends/runpod/configurator.py index eb4dfd7db..fa634df1e 100644 --- a/src/dstack/_internal/core/backends/runpod/configurator.py +++ b/src/dstack/_internal/core/backends/runpod/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -62,6 +63,7 @@ def _get_config(self, record: BackendRecord) -> RunpodConfig: ) def _validate_runpod_api_key(self, api_key: str): - client = api_client.RunpodApiClient(api_key=api_key) - if not client.validate_api_key(): + with closing(api_client.RunpodApiClient(api_key=api_key)) as client: + is_valid = client.validate_api_key() + if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_key"]]) diff --git a/src/dstack/_internal/core/backends/seeweb/configurator.py b/src/dstack/_internal/core/backends/seeweb/configurator.py index ebf89ca07..9368e73ca 100644 --- a/src/dstack/_internal/core/backends/seeweb/configurator.py +++ b/src/dstack/_internal/core/backends/seeweb/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -28,7 +29,9 @@ class SeewebConfigurator( BACKEND_CLASS = SeewebBackend def validate_config(self, config: SeewebBackendConfigWithCreds, default_creds_enabled: bool): - if not SeewebApiClient(config.creds.api_token).validate_api_key(): + with closing(SeewebApiClient(config.creds.api_token)) as client: + is_valid = client.validate_api_key() + if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_token"]]) def create_backend( diff --git a/src/dstack/_internal/core/backends/vastai/configurator.py b/src/dstack/_internal/core/backends/vastai/configurator.py index 6dde3c089..4fc1ff3bb 100644 --- a/src/dstack/_internal/core/backends/vastai/configurator.py +++ b/src/dstack/_internal/core/backends/vastai/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -68,6 +69,7 @@ def _get_config(self, record: BackendRecord) -> VastAIConfig: ) def _validate_vastai_creds(self, api_key: str): - client = api_client.VastAIAPIClient(api_key=api_key) - if not client.auth_test(): + with closing(api_client.VastAIAPIClient(api_key=api_key)) as client: + is_valid = client.auth_test() + if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_key"]]) diff --git a/src/dstack/_internal/core/backends/vultr/configurator.py b/src/dstack/_internal/core/backends/vultr/configurator.py index 9d70b2886..2bf2b4c4b 100644 --- a/src/dstack/_internal/core/backends/vultr/configurator.py +++ b/src/dstack/_internal/core/backends/vultr/configurator.py @@ -1,4 +1,5 @@ import json +from contextlib import closing from dstack._internal.core.backends.base.configurator import ( BackendRecord, @@ -70,6 +71,7 @@ def _get_config(self, record: BackendRecord) -> VultrConfig: ) def _validate_vultr_api_key(self, api_key: str): - client = api_client.VultrApiClient(api_key=api_key) - if not client.validate_api_key(): + with closing(api_client.VultrApiClient(api_key=api_key)) as client: + is_valid = client.validate_api_key() + if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_key"]]) From cbb4611ca36d9fc4450407e25bc5e44e5df1f81f Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:41:26 +0500 Subject: [PATCH 28/37] Report Vast.ai validation request failures as client errors --- src/dstack/_internal/core/backends/vastai/configurator.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/dstack/_internal/core/backends/vastai/configurator.py b/src/dstack/_internal/core/backends/vastai/configurator.py index 4fc1ff3bb..8c53c1d39 100644 --- a/src/dstack/_internal/core/backends/vastai/configurator.py +++ b/src/dstack/_internal/core/backends/vastai/configurator.py @@ -1,6 +1,8 @@ import json from contextlib import closing +import httpx2 + from dstack._internal.core.backends.base.configurator import ( BackendRecord, Configurator, @@ -15,6 +17,7 @@ VastAICreds, VastAIStoredConfig, ) +from dstack._internal.core.errors import ServerClientError from dstack._internal.core.models.backends.base import ( BackendType, ) @@ -70,6 +73,9 @@ def _get_config(self, record: BackendRecord) -> VastAIConfig: def _validate_vastai_creds(self, api_key: str): with closing(api_client.VastAIAPIClient(api_key=api_key)) as client: - is_valid = client.auth_test() + try: + is_valid = client.auth_test() + except httpx2.HTTPError as e: + raise ServerClientError(f"Failed to validate Vast.ai credentials: {e!r}") from e if not is_valid: raise_invalid_credentials_error(fields=[["creds", "api_key"]]) From 3928303b35a106252935456725020411404572a0 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:41:27 +0500 Subject: [PATCH 29/37] Close preset files response when iteration stops early --- src/dstack/api/server/_presets.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/dstack/api/server/_presets.py b/src/dstack/api/server/_presets.py index 2e41925bc..cb538e0f8 100644 --- a/src/dstack/api/server/_presets.py +++ b/src/dstack/api/server/_presets.py @@ -52,6 +52,8 @@ def _iter_chunks(resp: httpx2.Response) -> Iterator[bytes]: yield from resp.iter_bytes(chunk_size=_STREAM_CHUNK_SIZE) except httpx2.RequestError as e: raise ClientError(f"Failed to read preset files: {e!r}") from e + finally: + resp.close() def _iter_archives(chunks: Iterator[bytes]) -> Iterator[Tuple[str, bytes]]: From d664e9a5ef4bbf1f9312acfab78357d3ba77b67d Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 16:59:39 +0500 Subject: [PATCH 30/37] Drop redundant HTTP client tests --- src/tests/_internal/utils/test_http.py | 28 +--------------------- src/tests/api/server/test_api_client.py | 5 ---- src/tests/test_http_mock.py | 31 ------------------------- 3 files changed, 1 insertion(+), 63 deletions(-) diff --git a/src/tests/_internal/utils/test_http.py b/src/tests/_internal/utils/test_http.py index 55ee965cf..f434eabe9 100644 --- a/src/tests/_internal/utils/test_http.py +++ b/src/tests/_internal/utils/test_http.py @@ -5,7 +5,7 @@ import pytest from dstack._internal.utils import http -from dstack._internal.utils.http import USER_AGENT, AsyncHTTPClient, HTTPClient +from dstack._internal.utils.http import USER_AGENT, HTTPClient class TestHTTPClient: @@ -26,37 +26,11 @@ def test_uses_default_ssl_context(self, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(http, "get_default_ssl_context", lambda: ctx) assert _get_ssl_context(HTTPClient(timeout=5)) is ctx - @pytest.mark.parametrize("verify", [False, ssl.create_default_context()]) - def test_keeps_explicit_verify( - self, monkeypatch: pytest.MonkeyPatch, verify: Union[ssl.SSLContext, bool] - ): - monkeypatch.setattr(http, "get_default_ssl_context", _fail) - ctx = _get_ssl_context(HTTPClient(timeout=5, verify=verify)) - if isinstance(verify, ssl.SSLContext): - assert ctx is verify - else: - assert ctx.verify_mode == ssl.CERT_NONE - def test_does_not_build_ssl_context_with_transport(self, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(http, "get_default_ssl_context", _fail) HTTPClient(timeout=5, transport=httpx2.MockTransport(_echo_user_agent)) -class TestAsyncHTTPClient: - @pytest.mark.asyncio - async def test_sends_dstack_user_agent(self): - async def handler(request: httpx2.Request) -> httpx2.Response: - return _echo_user_agent(request) - - async with AsyncHTTPClient(timeout=5, transport=httpx2.MockTransport(handler)) as client: - assert (await client.get("http://test/")).text == USER_AGENT - - def test_uses_default_ssl_context(self, monkeypatch: pytest.MonkeyPatch): - ctx = ssl.create_default_context() - monkeypatch.setattr(http, "get_default_ssl_context", lambda: ctx) - assert _get_ssl_context(AsyncHTTPClient(timeout=5)) is ctx - - def _echo_user_agent(request: httpx2.Request) -> httpx2.Response: return httpx2.Response(200, text=request.headers["User-Agent"]) diff --git a/src/tests/api/server/test_api_client.py b/src/tests/api/server/test_api_client.py index 0f9405080..60cc8e336 100644 --- a/src/tests/api/server/test_api_client.py +++ b/src/tests/api/server/test_api_client.py @@ -155,11 +155,6 @@ def test_parses(self, base_url: str, expected: tuple): class TestAPIClientClose: - def test_closes_connections(self): - client = APIClient("https://server.test") - client.close() - assert client._client.is_closed - def test_closes_on_exiting_context(self): with APIClient("https://server.test") as client: pass diff --git a/src/tests/test_http_mock.py b/src/tests/test_http_mock.py index 744e5ede1..160f4abf4 100644 --- a/src/tests/test_http_mock.py +++ b/src/tests/test_http_mock.py @@ -20,34 +20,3 @@ def test_fails_unmatched_request(self, http_mock: HTTPMock): http_mock.get("https://api.test/items?kind=a") with httpx2.Client() as client, pytest.raises(AssertionError, match="No mocked response"): client.get("https://api.test/items", params={"kind": "b"}) - - def test_later_registration_takes_precedence(self, http_mock: HTTPMock): - http_mock.get("https://api.test/items", text="old") - http_mock.get("https://api.test/items", text="new") - with httpx2.Client() as client: - assert client.get("https://api.test/items").text == "new" - - def test_responds_from_list_and_repeats_last(self, http_mock: HTTPMock): - http_mock.get("https://api.test/items", [{"status_code": 503}, {"json": [1]}]) - with httpx2.Client() as client: - statuses = [client.get("https://api.test/items").status_code for _ in range(3)] - assert statuses == [503, 200, 200] - - @pytest.mark.parametrize("exc", [httpx2.ConnectError, httpx2.ReadTimeout("slow")]) - def test_raises_exc(self, http_mock: HTTPMock, exc): - http_mock.get("https://api.test/items", exc=exc) - with httpx2.Client() as client, pytest.raises(httpx2.TransportError): - client.get("https://api.test/items") - - def test_mocks_unix_socket_transport(self, http_mock: HTTPMock): - http_mock.get("http://localhost/api/healthcheck", json={"ok": True}) - transport = httpx2.HTTPTransport(uds="/nonexistent.sock") - with httpx2.Client(transport=transport, base_url="http://localhost") as client: - assert client.get("/api/healthcheck").json() == {"ok": True} - - @pytest.mark.asyncio - async def test_mocks_async_clients(self, http_mock: HTTPMock): - http_mock.get("https://api.test/items", json=[1]) - async with httpx2.AsyncClient() as client: - assert (await client.get("https://api.test/items")).json() == [1] - assert http_mock.last_request.timeout["read"] == 5.0 From 175a86e372baff8fe90158e0eae87c508d19dc3c Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 17:01:14 +0500 Subject: [PATCH 31/37] Don't close a gateway connection again after it was removed while opening Connections to the same gateway share the SSH control socket, so the second close could close a replacement's tunnel. --- .../_internal/server/services/gateways/pool.py | 18 +++++++++++------- .../server/services/gateways/test_pool.py | 1 + 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/dstack/_internal/server/services/gateways/pool.py b/src/dstack/_internal/server/services/gateways/pool.py index 21fcea5ea..ad763f0cd 100644 --- a/src/dstack/_internal/server/services/gateways/pool.py +++ b/src/dstack/_internal/server/services/gateways/pool.py @@ -31,14 +31,18 @@ async def get_or_add( return connection except Exception: async with self._lock: - # The connection may have been removed and replaced while opening. - if self._connections.get(hostname) is connection: + # The connection may have been removed (and closed) while opening. + removed_here = self._connections.get(hostname) is connection + if removed_here: del self._connections[hostname] - # Opening may have failed after starting the SSH tunnel. - try: - await connection.close() - except Exception: - logger.exception("Failed to close the gateway connection to %s", hostname) + if removed_here: + # Opening may have failed after starting the SSH tunnel. Only close it here + # if nothing else removed it: connections to the same gateway share their + # SSH control socket, so closing twice can close a replacement's tunnel. + try: + await connection.close() + except Exception: + logger.exception("Failed to close the gateway connection to %s", hostname) raise async def remove(self, hostname: str) -> bool: diff --git a/src/tests/_internal/server/services/gateways/test_pool.py b/src/tests/_internal/server/services/gateways/test_pool.py index 297610e6c..a5dbe7572 100644 --- a/src/tests/_internal/server/services/gateways/test_pool.py +++ b/src/tests/_internal/server/services/gateways/test_pool.py @@ -53,5 +53,6 @@ async def remove_and_replace(**kwargs): with pytest.raises(RuntimeError, match="ssh failed"): await pool.get_or_add("gateway.test", "key") + failed.close.assert_awaited_once() # by remove(), not again after the failed open replacement.close.assert_not_awaited() assert await pool.all() == [replacement] From dece3d1001bf4dfbec46c8bb8091ffc851e1e6be Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 17:01:15 +0500 Subject: [PATCH 32/37] Don't reopen tunnels of closed gateway connections --- .../server/services/gateways/connection.py | 4 ++++ .../services/gateways/test_connection.py | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/dstack/_internal/server/services/gateways/connection.py b/src/dstack/_internal/server/services/gateways/connection.py index 650c01b2d..5846dab20 100644 --- a/src/dstack/_internal/server/services/gateways/connection.py +++ b/src/dstack/_internal/server/services/gateways/connection.py @@ -77,6 +77,8 @@ def __init__(self, ip_address: str, id_rsa: str, server_port: int): async def check_or_restart(self) -> bool: async with self._lock.writer_lock: + if self._closed: + return False if not await self.tunnel.acheck(): logger.info("Connection to gateway %s is down, restarting", self.ip_address) await self._open_tunnel() @@ -85,6 +87,8 @@ async def check_or_restart(self) -> bool: async def open(self, close_existing_tunnel: bool = False) -> None: async with self._lock.writer_lock: + if self._closed: + raise GatewayError(f"Connection to gateway {self.ip_address} is closed") if close_existing_tunnel: # Close remaining tunnel if previous server process died w/o graceful shutdown if await self.tunnel.acheck(): diff --git a/src/tests/_internal/server/services/gateways/test_connection.py b/src/tests/_internal/server/services/gateways/test_connection.py index 295c4eac4..677335049 100644 --- a/src/tests/_internal/server/services/gateways/test_connection.py +++ b/src/tests/_internal/server/services/gateways/test_connection.py @@ -37,3 +37,21 @@ async def test_client_raises_gateway_error_after_close( with pytest.raises(GatewayError): async with conn.client(): pass + + @pytest.mark.asyncio + async def test_does_not_reopen_tunnel_after_close( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ): + monkeypatch.setattr(settings, "SERVER_DIR_PATH", tmp_path) + conn = GatewayConnection(ip_address="10.0.0.1", id_rsa="key", server_port=3000) + monkeypatch.setattr(conn.tunnel, "aclose", AsyncMock()) + monkeypatch.setattr(conn.tunnel, "acheck", AsyncMock(return_value=False)) + tunnel_aopen = AsyncMock() + monkeypatch.setattr(conn.tunnel, "aopen", tunnel_aopen) + + await conn.close() + + assert not await conn.check_or_restart() + with pytest.raises(GatewayError): + await conn.open() + tunnel_aopen.assert_not_awaited() From a348e9ff7710362caadd8c2ac856dbb9d230e096 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 17:01:15 +0500 Subject: [PATCH 33/37] Raise a resolve error for invalid URLs in resolve_url --- src/dstack/_internal/cli/utils/common.py | 2 +- src/tests/_internal/cli/utils/test_common.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/dstack/_internal/cli/utils/common.py b/src/dstack/_internal/cli/utils/common.py index e4e2cbf45..7a1b61f0b 100644 --- a/src/dstack/_internal/cli/utils/common.py +++ b/src/dstack/_internal/cli/utils/common.py @@ -176,7 +176,7 @@ def resolve_url(url: str, timeout: float = 5.0) -> str: try: with HTTPClient(timeout=timeout, follow_redirects=True) as client: response = client.get(url) - except httpx2.HTTPError as e: + except (httpx2.HTTPError, httpx2.InvalidURL) as e: raise ValueError(f"Failed to resolve url {url}") from e return str(response.url) diff --git a/src/tests/_internal/cli/utils/test_common.py b/src/tests/_internal/cli/utils/test_common.py index ed05a5775..7c2da718a 100644 --- a/src/tests/_internal/cli/utils/test_common.py +++ b/src/tests/_internal/cli/utils/test_common.py @@ -203,3 +203,7 @@ def test_raises_value_error_on_request_errors(self, http_mock: HTTPMock, exc: Ex with pytest.raises(ValueError, match="Failed to resolve url http://server.test"): resolve_url("server.test") + + def test_raises_value_error_on_invalid_url(self): + with pytest.raises(ValueError, match="Failed to resolve url"): + resolve_url("http://server.test:abc") From e40784ff2fee52f4607875a1598a30900b62ccfc Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 17:02:29 +0500 Subject: [PATCH 34/37] Fix preset files test for the closed response --- src/tests/_internal/cli/services/presets/test_registry.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/tests/_internal/cli/services/presets/test_registry.py b/src/tests/_internal/cli/services/presets/test_registry.py index cabb1d21f..042d4a86a 100644 --- a/src/tests/_internal/cli/services/presets/test_registry.py +++ b/src/tests/_internal/cli/services/presets/test_registry.py @@ -327,7 +327,9 @@ def frame(path: str, blob: bytes) -> bytes: # Framed values are read across chunk boundaries, so a chunk size that # splits every frame is what proves the reader, not the framing. chunks = [stream[i : i + 3] for i in range(0, len(stream), 3)] - client, calls = self._client(SimpleNamespace(iter_bytes=lambda chunk_size: iter(chunks))) + response = SimpleNamespace(iter_bytes=lambda chunk_size: iter(chunks), closed=False) + response.close = lambda: setattr(response, "closed", True) + client, calls = self._client(response) got = list(client.get_files("main", "qwen38")) @@ -335,6 +337,7 @@ def frame(path: str, blob: bytes) -> bytes: assert call.path == "/api/project/main/presets/get_files" assert call.kwargs["stream"] is True assert got == [("patch/a.txt", b"tar-a"), ("run.sh", b"tar-b")] + assert response.closed class TestPushPresetToRegistry: From 0327ae9065eb71f395e4bed81f970c1b00e4cb17 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 17:15:18 +0500 Subject: [PATCH 35/37] Add contributing notes on HTTP requests --- contributing/HTTP.md | 54 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 contributing/HTTP.md diff --git a/contributing/HTTP.md b/contributing/HTTP.md new file mode 100644 index 000000000..4266c2340 --- /dev/null +++ b/contributing/HTTP.md @@ -0,0 +1,54 @@ +# HTTP requests + +`dstack` makes HTTP requests with [httpx2](https://github.com/pydantic/httpx2), Pydantic's maintained fork of httpx with the same API: the Python API and the CLI call the server, the server calls runners and shims, backend APIs, gateways, and service replicas, and the gateway calls the server. `requests` remains only as a dependency of third-party libraries, e.g. python-dxf for Docker registries. + +## Clients + +Create clients with `HTTPClient` or `AsyncHTTPClient` from `dstack._internal.utils.http`, or subclass them, rather than with `httpx2.Client` and `httpx2.AsyncClient`. They add dstack defaults: + +- `timeout` is required. See [Timeouts](#timeouts). +- `verify=True` trusts the system CA certificates, or the certifi bundle on systems without them (`get_default_ssl_context()`). `SSL_CERT_FILE` and `SSL_CERT_DIR` override the system store. `REQUESTS_CA_BUNDLE` and `CURL_CA_BUNDLE` don't apply. +- Requests send `User-Agent: dstack/`. +- Redirects are not followed, as in httpx2. Pass `follow_redirects=True` for external APIs that may redirect, as `requests` did. Never follow redirects in clients that proxy responses: the redirect belongs to the downstream client. Some backend clients don't follow redirects on purpose, e.g. so that a redirect cannot replay a request that launches an instance. + +Building a client with `verify=True` loads the CA certificates, which takes a few milliseconds on Linux. Clients that only talk plain HTTP don't need them: + +- For Unix sockets, use `make_uds_transport()` or `make_async_uds_transport()`, which build no SSL context. A client given a transport ignores its own `verify`. +- For plain `http://` URLs without a custom transport, pass `verify=False`. + +## Timeouts + +A number passed as `timeout` sets four httpx2 timeouts: connect (including the TLS handshake), read, write, and pool (waiting for a free connection from the client's pool). Each limits one wait, not the whole request: the read timeout limits the time to the first response bytes and every gap between chunks after that. A streamed response that keeps sending data never times out. + +Choose the timeout from the slowest legitimate wait of the endpoints the client calls. Use `httpx2.Timeout(..., connect=...)` to fail fast on unreachable hosts while allowing slow responses, and pass `timeout=` per request where one endpoint needs longer than the client's default. + +## Lifecycle + +An object that makes repeated requests owns one client, reuses its connection pool, and closes it when it's done: + +- Backend API clients create their client once and have a `close()`, which `Compute.close()` calls. Configurators close the API clients they create for credentials validation. +- Gateway connections close their clients when they are closed. + +One-off requests use a short-lived client: `with HTTPClient(...) as client:`. + +Async clients are bound to the event loop that first uses them. Don't share them across event loops, and don't create them at module level. + +## Async code + +In async code, use `AsyncHTTPClient`. A sync request blocks the event loop and everything else the server or gateway does meanwhile. Code that has to use a sync client or SDK runs it with `run_async()`. + +As with any network call, never make HTTP requests inside a DB session or transaction (see [DATABASE.md](DATABASE.md)). + +## Errors and retries + +- `httpx2.HTTPError` covers every failure: transport errors (`httpx2.RequestError`) and the `httpx2.HTTPStatusError` that `raise_for_status()` raises. `raise_for_status()` also raises on 1xx and 3xx responses. +- `httpx2.RequestError` covers requests that got no response: connect errors and timeouts, read and write errors, and `RemoteProtocolError` when the server closes the connection without a response. +- A `ConnectTimeout` is a `TimeoutException`, not a `ConnectError`. Catch both when handling "could not connect". +- `httpx2.InvalidURL` is not an `HTTPError`. +- `Response.json()` raises `ValueError`: `json.JSONDecodeError`, or `UnicodeDecodeError` for bodies that are not UTF-8. + +Retry a request that changes state only if it can't have reached the server: on `ConnectError` and `ConnectTimeout`. After other errors, e.g. `RemoteProtocolError` or `ReadTimeout`, the server may have processed it. + +## Tests + +Tests mock HTTP responses with the `http_mock` fixture (`src/tests/http_mock.py`). It patches the httpx2 transports, including Unix socket ones, so code under test needs no changes. Requests that match no registered URL fail the test. From e224d5d84884c8160a6d155a01a2e06de6e89c40 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 17:17:32 +0500 Subject: [PATCH 36/37] Mention HTTP clients in ARCHITECTURE.md instead of a separate doc --- contributing/ARCHITECTURE.md | 2 +- contributing/HTTP.md | 54 ------------------------------------ 2 files changed, 1 insertion(+), 55 deletions(-) delete mode 100644 contributing/HTTP.md diff --git a/contributing/ARCHITECTURE.md b/contributing/ARCHITECTURE.md index ca14f3624..08512cced 100644 --- a/contributing/ARCHITECTURE.md +++ b/contributing/ARCHITECTURE.md @@ -42,7 +42,7 @@ When all job's commands are executed, the runner marks job as done, the containe ## Project structure -The server is a FastAPI app backend by SQLite or Postgres. The runner and shim are written in Go. +The server is a FastAPI app backend by SQLite or Postgres. The runner and shim are written in Go. HTTP clients use [httpx2](https://github.com/pydantic/httpx2); create them with `HTTPClient` and `AsyncHTTPClient` from `dstack._internal.utils.http`. * `docker/` – Dockefiles for `dstack` images * `docs/` – source files for mkdocs generated documentation diff --git a/contributing/HTTP.md b/contributing/HTTP.md deleted file mode 100644 index 4266c2340..000000000 --- a/contributing/HTTP.md +++ /dev/null @@ -1,54 +0,0 @@ -# HTTP requests - -`dstack` makes HTTP requests with [httpx2](https://github.com/pydantic/httpx2), Pydantic's maintained fork of httpx with the same API: the Python API and the CLI call the server, the server calls runners and shims, backend APIs, gateways, and service replicas, and the gateway calls the server. `requests` remains only as a dependency of third-party libraries, e.g. python-dxf for Docker registries. - -## Clients - -Create clients with `HTTPClient` or `AsyncHTTPClient` from `dstack._internal.utils.http`, or subclass them, rather than with `httpx2.Client` and `httpx2.AsyncClient`. They add dstack defaults: - -- `timeout` is required. See [Timeouts](#timeouts). -- `verify=True` trusts the system CA certificates, or the certifi bundle on systems without them (`get_default_ssl_context()`). `SSL_CERT_FILE` and `SSL_CERT_DIR` override the system store. `REQUESTS_CA_BUNDLE` and `CURL_CA_BUNDLE` don't apply. -- Requests send `User-Agent: dstack/`. -- Redirects are not followed, as in httpx2. Pass `follow_redirects=True` for external APIs that may redirect, as `requests` did. Never follow redirects in clients that proxy responses: the redirect belongs to the downstream client. Some backend clients don't follow redirects on purpose, e.g. so that a redirect cannot replay a request that launches an instance. - -Building a client with `verify=True` loads the CA certificates, which takes a few milliseconds on Linux. Clients that only talk plain HTTP don't need them: - -- For Unix sockets, use `make_uds_transport()` or `make_async_uds_transport()`, which build no SSL context. A client given a transport ignores its own `verify`. -- For plain `http://` URLs without a custom transport, pass `verify=False`. - -## Timeouts - -A number passed as `timeout` sets four httpx2 timeouts: connect (including the TLS handshake), read, write, and pool (waiting for a free connection from the client's pool). Each limits one wait, not the whole request: the read timeout limits the time to the first response bytes and every gap between chunks after that. A streamed response that keeps sending data never times out. - -Choose the timeout from the slowest legitimate wait of the endpoints the client calls. Use `httpx2.Timeout(..., connect=...)` to fail fast on unreachable hosts while allowing slow responses, and pass `timeout=` per request where one endpoint needs longer than the client's default. - -## Lifecycle - -An object that makes repeated requests owns one client, reuses its connection pool, and closes it when it's done: - -- Backend API clients create their client once and have a `close()`, which `Compute.close()` calls. Configurators close the API clients they create for credentials validation. -- Gateway connections close their clients when they are closed. - -One-off requests use a short-lived client: `with HTTPClient(...) as client:`. - -Async clients are bound to the event loop that first uses them. Don't share them across event loops, and don't create them at module level. - -## Async code - -In async code, use `AsyncHTTPClient`. A sync request blocks the event loop and everything else the server or gateway does meanwhile. Code that has to use a sync client or SDK runs it with `run_async()`. - -As with any network call, never make HTTP requests inside a DB session or transaction (see [DATABASE.md](DATABASE.md)). - -## Errors and retries - -- `httpx2.HTTPError` covers every failure: transport errors (`httpx2.RequestError`) and the `httpx2.HTTPStatusError` that `raise_for_status()` raises. `raise_for_status()` also raises on 1xx and 3xx responses. -- `httpx2.RequestError` covers requests that got no response: connect errors and timeouts, read and write errors, and `RemoteProtocolError` when the server closes the connection without a response. -- A `ConnectTimeout` is a `TimeoutException`, not a `ConnectError`. Catch both when handling "could not connect". -- `httpx2.InvalidURL` is not an `HTTPError`. -- `Response.json()` raises `ValueError`: `json.JSONDecodeError`, or `UnicodeDecodeError` for bodies that are not UTF-8. - -Retry a request that changes state only if it can't have reached the server: on `ConnectError` and `ConnectTimeout`. After other errors, e.g. `RemoteProtocolError` or `ReadTimeout`, the server may have processed it. - -## Tests - -Tests mock HTTP responses with the `http_mock` fixture (`src/tests/http_mock.py`). It patches the httpx2 transports, including Unix socket ones, so code under test needs no changes. Requests that match no registered URL fail the test. From 655bf06ae3393d0d0baad36b644f3cb1f9e73bb1 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 17:18:34 +0500 Subject: [PATCH 37/37] Move the HTTP clients note to a Misc section --- contributing/ARCHITECTURE.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/contributing/ARCHITECTURE.md b/contributing/ARCHITECTURE.md index 08512cced..7ad61b802 100644 --- a/contributing/ARCHITECTURE.md +++ b/contributing/ARCHITECTURE.md @@ -42,7 +42,7 @@ When all job's commands are executed, the runner marks job as done, the containe ## Project structure -The server is a FastAPI app backend by SQLite or Postgres. The runner and shim are written in Go. HTTP clients use [httpx2](https://github.com/pydantic/httpx2); create them with `HTTPClient` and `AsyncHTTPClient` from `dstack._internal.utils.http`. +The server is a FastAPI app backend by SQLite or Postgres. The runner and shim are written in Go. * `docker/` – Dockefiles for `dstack` images * `docs/` – source files for mkdocs generated documentation @@ -84,3 +84,7 @@ The server is a FastAPI app backend by SQLite or Postgres. The runner and shim a * `openai/` - OpenAI API proxy * `registry/` - gateway services registry * `systemd/` - systemd service files + +## Misc + +* HTTP clients use [httpx2](https://github.com/pydantic/httpx2). Create them with `HTTPClient` and `AsyncHTTPClient` from `dstack._internal.utils.http`.