From 33fd1262f2e7348baf01950583fcfc3f2fdb4ba0 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 12:14:35 +0500 Subject: [PATCH 1/5] Migrate from httpx to httpx2 --- pyproject.toml | 11 +- .../core/backends/vastai/api_client.py | 6 +- src/dstack/_internal/proxy/gateway/auth.py | 14 +- src/dstack/_internal/proxy/gateway/otel.py | 3 +- .../proxy/gateway/services/server_client.py | 22 +-- .../lib/services/model_proxy/clients/tgi.py | 12 +- .../lib/services/model_proxy/model_proxy.py | 4 +- .../lib/services/model_proxy/passthrough.py | 12 +- .../proxy/lib/services/service_connection.py | 13 +- .../pipeline_tasks/gateway_replicas.py | 2 +- .../background/scheduled_tasks/gateways.py | 4 +- .../background/scheduled_tasks/probes.py | 4 +- .../server/services/gateways/__init__.py | 4 +- .../server/services/gateways/client.py | 6 +- .../services/jobs/job_replica_http_client.py | 2 +- .../server/services/jobs/server_connection.py | 8 +- .../server/services/logs/fluentbit.py | 8 +- .../services/proxy/services/service_proxy.py | 26 ++-- .../services/runs/router_worker_sync.py | 2 +- .../_internal/server/utils/otel/utils.py | 4 +- .../proxy/gateway/routers/test_config.py | 6 +- .../proxy/gateway/routers/test_metering.py | 4 +- .../proxy/gateway/routers/test_registry.py | 6 +- .../proxy/gateway/routers/test_services.py | 6 +- .../proxy/gateway/routers/test_state.py | 6 +- .../proxy/gateway/routers/test_stats.py | 6 +- .../gateway/services/test_server_client.py | 16 +-- .../_internal/proxy/gateway/test_auth.py | 66 ++++----- .../proxy/lib/routers/test_model_proxy.py | 46 +++--- .../pipeline_tasks/test_gateway_replicas.py | 2 +- src/tests/_internal/server/conftest.py | 6 +- .../_internal/server/routers/test_auth.py | 2 +- .../_internal/server/routers/test_backends.py | 2 +- .../_internal/server/routers/test_events.py | 2 +- .../_internal/server/routers/test_exports.py | 2 +- .../_internal/server/routers/test_files.py | 2 +- .../_internal/server/routers/test_fleets.py | 2 +- .../_internal/server/routers/test_gateways.py | 2 +- .../_internal/server/routers/test_gpus.py | 2 +- .../_internal/server/routers/test_imports.py | 2 +- .../server/routers/test_instances.py | 2 +- .../_internal/server/routers/test_logs.py | 2 +- .../_internal/server/routers/test_metrics.py | 2 +- .../_internal/server/routers/test_projects.py | 2 +- .../server/routers/test_prometheus.py | 2 +- .../server/routers/test_public_keys.py | 2 +- .../_internal/server/routers/test_repos.py | 2 +- .../_internal/server/routers/test_runs.py | 2 +- .../_internal/server/routers/test_secrets.py | 2 +- .../_internal/server/routers/test_server.py | 2 +- .../_internal/server/routers/test_sshproxy.py | 2 +- .../server/routers/test_templates.py | 2 +- .../_internal/server/routers/test_users.py | 2 +- .../_internal/server/routers/test_volumes.py | 2 +- .../server/services/logs/test_fluentbit.py | 10 +- .../proxy/routers/test_service_proxy.py | 10 +- .../services/runs/test_router_worker_sync.py | 136 +++++++++--------- src/tests/_internal/server/test_app.py | 2 +- 58 files changed, 267 insertions(+), 274 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 857ee99e12..ddd3962bf7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -219,10 +219,7 @@ gateway = [ "uvloop>=0.18.0; sys_platform != 'win32' and platform_python_implementation != 'PyPy'", "aiorwlock", "aiocache", - "httpx>=0.28.0", - # Gateway authorization and requests to services need the pool cancellation and recovery - # fixes in httpx2 (#4338). - "httpx2>=2.13.1", + "httpx2>=2.16.2", "jinja2", # Always installed so that OpenTelemetry can be enabled without reinstalling the gateway. "opentelemetry-sdk>=1.39.0", @@ -238,9 +235,7 @@ server = [ "uvicorn[standard]", "aiorwlock", "aiocache", - "httpx>=0.28.0", - # Requests to services need the pool cancellation and recovery fixes in httpx2 (#4338). - "httpx2>=2.13.1", + "httpx2>=2.16.2", "jinja2", "watchfiles", "sqlalchemy[asyncio]>=2.0.0", @@ -324,7 +319,7 @@ otel = [ "opentelemetry-exporter-prometheus>=0.51b0", "opentelemetry-instrumentation-fastapi>=0.51b0", "opentelemetry-instrumentation-sqlalchemy>=0.51b0", - "opentelemetry-instrumentation-httpx>=0.51b0", + "opentelemetry-instrumentation-httpx>=0.65b0", "opentelemetry-instrumentation-requests>=0.51b0", "opentelemetry-instrumentation-system-metrics>=0.51b0", "opentelemetry-instrumentation-logging>=0.61b0", diff --git a/src/dstack/_internal/core/backends/vastai/api_client.py b/src/dstack/_internal/core/backends/vastai/api_client.py index c39d856c99..f59febcd80 100644 --- a/src/dstack/_internal/core/backends/vastai/api_client.py +++ b/src/dstack/_internal/core/backends/vastai/api_client.py @@ -1,7 +1,7 @@ import json from typing import Optional, Union -import httpx +import httpx2 import dstack._internal.utils.docker as docker from dstack._internal.core.consts import DSTACK_RUNNER_SSH_PORT @@ -32,7 +32,7 @@ def __init__( class VastAIAPIClient: def __init__(self, api_key: str): - self.s = httpx.Client( + self.s = httpx2.Client( base_url="https://console.vast.ai/api/", headers={"Authorization": f"Bearer {api_key}"}, timeout=30, @@ -124,5 +124,5 @@ def auth_test(self) -> bool: try: self.s.get("/v1/instances/").raise_for_status() return True - except httpx.HTTPError: + except httpx2.HTTPError: return False diff --git a/src/dstack/_internal/proxy/gateway/auth.py b/src/dstack/_internal/proxy/gateway/auth.py index d98c67791c..1e7cc256ea 100644 --- a/src/dstack/_internal/proxy/gateway/auth.py +++ b/src/dstack/_internal/proxy/gateway/auth.py @@ -3,7 +3,7 @@ from typing import Optional from urllib.parse import quote -import httpx2 as httpx +import httpx2 from aiocache import cached from fastapi import status from pydantic import BaseModel @@ -34,7 +34,7 @@ class _ProjectAccess: class GatewayProxyAuthProvider(BaseProxyAuthProvider): - def __init__(self, server_client: httpx.AsyncClient) -> None: + def __init__(self, server_client: httpx2.AsyncClient) -> None: self._server_client = server_client async def is_project_member(self, project_name: str, token: str) -> bool: @@ -62,7 +62,7 @@ async def _get_project_access(self, project_name: str, token: str) -> _ProjectAc ) if resp is None: return _ProjectAccess(project_id=None) - if resp.status_code == httpx.codes.NOT_FOUND: + if resp.status_code == httpx2.codes.NOT_FOUND: return _ProjectAccess(project_id=None, project_exists=False) project = _Project.model_validate_json(resp.content) return _ProjectAccess( @@ -88,7 +88,7 @@ async def _get_user(self, token: str) -> Optional["_User"]: async def _request( self, path: str, token: str, allow_not_found: bool = False - ) -> Optional[httpx.Response]: + ) -> Optional[httpx2.Response]: """ Returns `None` if the server denies access with the token. With `allow_not_found`, returns the server's 404 response instead of raising. @@ -97,11 +97,11 @@ async def _request( resp = await self._server_client.post( path, headers={"Authorization": f"Bearer {token}"} ) - if resp.status_code == httpx.codes.FORBIDDEN: + if resp.status_code == httpx2.codes.FORBIDDEN: return None - if not (allow_not_found and resp.status_code == httpx.codes.NOT_FOUND): + if not (allow_not_found and resp.status_code == httpx2.codes.NOT_FOUND): resp.raise_for_status() - except httpx.HTTPError as e: + except httpx2.HTTPError as e: raise UnexpectedProxyError( f"Failed requesting dstack-server to check access: {e!r}" ) from e diff --git a/src/dstack/_internal/proxy/gateway/otel.py b/src/dstack/_internal/proxy/gateway/otel.py index 88b0fb8d58..840eaac63a 100644 --- a/src/dstack/_internal/proxy/gateway/otel.py +++ b/src/dstack/_internal/proxy/gateway/otel.py @@ -6,7 +6,7 @@ from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor -from opentelemetry.instrumentation.httpx import HTTPX2ClientInstrumentor, HTTPXClientInstrumentor +from opentelemetry.instrumentation.httpx import HTTPX2ClientInstrumentor from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.sdk.resources import Resource @@ -27,7 +27,6 @@ def instrument(app: FastAPI) -> None: """Must be called before the app starts serving. No-op until `apply_settings` is called.""" FastAPIInstrumentor.instrument_app(app) - HTTPXClientInstrumentor().instrument() HTTPX2ClientInstrumentor().instrument() SystemMetricsInstrumentor(config=otel_utils.PROCESS_METRICS_CONFIG).instrument() diff --git a/src/dstack/_internal/proxy/gateway/services/server_client.py b/src/dstack/_internal/proxy/gateway/services/server_client.py index 06c3b781ec..4e6979a015 100644 --- a/src/dstack/_internal/proxy/gateway/services/server_client.py +++ b/src/dstack/_internal/proxy/gateway/services/server_client.py @@ -5,7 +5,7 @@ from pathlib import Path from typing import Container, Dict, Generator, List -import httpx2 as httpx +import httpx2 logger = logging.getLogger(__name__) BASE_URL = "http://dstack/" # any hostname will work @@ -15,7 +15,7 @@ class CachedClientInfo: """HTTP client and connection-failure history for one server, owned by HTTPMultiClient.""" - client: httpx.AsyncClient + client: httpx2.AsyncClient socket: Path connect_errors: List[datetime.datetime] = field(default_factory=lambda: []) @@ -26,12 +26,12 @@ def seems_disconnected(self) -> bool: return self.connect_errors[-1] - self.connect_errors[0] >= datetime.timedelta(minutes=2) -class HTTPMultiClient(httpx.AsyncClient): +class HTTPMultiClient(httpx2.AsyncClient): """Gateway HTTP client for uncached project-access checks against dstack-server. GatewayProxyAuthProvider uses this client and owns authorization decisions and their cache. Return the server's HTTP response, including error statuses. Raise - httpx.RequestError when no connected server can complete the request. + httpx2.RequestError when no connected server can complete the request. """ def __init__(self, sockets_dir: Path): @@ -39,8 +39,8 @@ def __init__(self, sockets_dir: Path): self._sockets_dir = sockets_dir.expanduser() self._clients_cache: Dict[str, CachedClientInfo] = {} - async def send(self, request: httpx.Request, *args, **kwargs) -> httpx.Response: - errors: List[httpx.RequestError] = [] + async def send(self, request: httpx2.Request, *args, **kwargs) -> httpx2.Response: + errors: List[httpx2.RequestError] = [] clients_count = 0 # Try another replica after request errors; HTTP error responses are returned. @@ -49,7 +49,7 @@ async def send(self, request: httpx.Request, *args, **kwargs) -> httpx.Response: resp = await client.client.send(request, *args, **kwargs) client.connect_errors = [] return resp - except httpx.ConnectError: + except httpx2.ConnectError: client.connect_errors.append(datetime.datetime.now()) if client.seems_disconnected(): logging.debug( @@ -57,7 +57,7 @@ async def send(self, request: httpx.Request, *args, **kwargs) -> httpx.Response: client.socket, ) client.socket.unlink() - except httpx.RequestError as e: + except httpx2.RequestError as e: errors.append(e) logger.warning("Request failed with socket %s: %r", client.socket, e) @@ -68,7 +68,7 @@ async def send(self, request: httpx.Request, *args, **kwargs) -> httpx.Response: msg += f"all {clients_count} socket(s) in {self._sockets_dir} are disconnected" else: msg += f"{len(errors)} socket(s) failed. Last error: {errors[-1]!r}" - raise httpx.RequestError(msg, request=request) + raise httpx2.RequestError(msg, request=request) def _iter_clients_rand(self) -> Generator[CachedClientInfo, None, None]: sockets = list(self._sockets_dir.glob("*.sock")) @@ -85,8 +85,8 @@ def _iter_clients_rand(self) -> Generator[CachedClientInfo, None, None]: @staticmethod def _make_client(socket: Path) -> CachedClientInfo: - client = httpx.AsyncClient( - transport=httpx.AsyncHTTPTransport(uds=str(socket.absolute())), + client = httpx2.AsyncClient( + transport=httpx2.AsyncHTTPTransport(uds=str(socket.absolute())), base_url=BASE_URL, ) return CachedClientInfo( diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/tgi.py b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/tgi.py index 84165558ea..9996f0cdcf 100644 --- a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/tgi.py +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/tgi.py @@ -3,7 +3,7 @@ import uuid from typing import AsyncIterator, Dict, List -import httpx2 as httpx +import httpx2 import jinja2 import jinja2.sandbox from fastapi import status @@ -23,7 +23,7 @@ class TGIChatCompletions(ChatCompletionsClient): # https://huggingface.github.io/text-generation-inference/ - def __init__(self, http_client: httpx.AsyncClient, chat_template: str, eos_token: str): + def __init__(self, http_client: httpx2.AsyncClient, chat_template: str, eos_token: str): self.client = http_client self.eos_token = eos_token @@ -41,7 +41,7 @@ async def generate(self, request: ChatCompletionsRequest) -> ChatCompletionsResp try: resp = await self.client.post("/generate", json=payload) await self.propagate_error(resp) - except httpx.RequestError as e: + except httpx2.RequestError as e: raise ProxyError(f"Error requesting model: {e!r}", status.HTTP_502_BAD_GATEWAY) data = resp.json() @@ -105,7 +105,7 @@ async def stream(self, request: ChatCompletionsRequest) -> AsyncIterator[ChatCom completion_id=completion_id, created=created, ) - except httpx.RequestError as e: + except httpx2.RequestError as e: raise ProxyError(f"Error requesting model: {e!r}", status.HTTP_502_BAD_GATEWAY) def parse_chunk( @@ -194,10 +194,10 @@ def trim_stop_tokens(text: str, stop_tokens: List[str]) -> str: return text @staticmethod - async def propagate_error(resp: httpx.Response) -> None: + async def propagate_error(resp: httpx2.Response) -> None: """ Propagates HTTP error by raising ProxyError if status is not 200. - May also raise httpx.RequestError if there are issues reading the response. + May also raise httpx2.RequestError if there are issues reading the response. """ if resp.status_code != 200: resp_body = await resp.aread() diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/model_proxy.py b/src/dstack/_internal/proxy/lib/services/model_proxy/model_proxy.py index 5a19efab7e..772980edca 100644 --- a/src/dstack/_internal/proxy/lib/services/model_proxy/model_proxy.py +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/model_proxy.py @@ -1,4 +1,4 @@ -import httpx2 as httpx +import httpx2 from dstack._internal.proxy.lib.errors import UnexpectedProxyError from dstack._internal.proxy.lib.models import ChatModel @@ -6,7 +6,7 @@ from dstack._internal.proxy.lib.services.model_proxy.clients.tgi import TGIChatCompletions -def get_chat_client(model: ChatModel, http_client: httpx.AsyncClient) -> ChatCompletionsClient: +def get_chat_client(model: ChatModel, http_client: httpx2.AsyncClient) -> ChatCompletionsClient: if model.format_spec.format == "tgi": return TGIChatCompletions( http_client=http_client, diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/passthrough.py b/src/dstack/_internal/proxy/lib/services/model_proxy/passthrough.py index f13ef4678b..33f7d256b4 100644 --- a/src/dstack/_internal/proxy/lib/services/model_proxy/passthrough.py +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/passthrough.py @@ -6,7 +6,7 @@ import asyncio from typing import Annotated, Any, AsyncIterator, Coroutine, Optional, TypeVar -import httpx2 as httpx +import httpx2 from fastapi import Request, Response, status from fastapi.responses import StreamingResponse from pydantic import BaseModel, ConfigDict, Field, ValidationError @@ -74,7 +74,7 @@ async def forward_chat_completions( upstream_response = await _run_until_disconnect( request, client.send(upstream_request, stream=True) ) - except httpx.RequestError as e: + except httpx2.RequestError as e: raise ProxyError(f"Error requesting model: {e!r}", status.HTTP_502_BAD_GATEWAY) # A service that ignores `stream` responds with JSON, which is not a stream content_type = upstream_response.headers.get("content-type", "") @@ -88,7 +88,7 @@ async def forward_chat_completions( ) try: content = await _run_until_disconnect(request, upstream_response.aread()) - except httpx.RequestError as e: + except httpx2.RequestError as e: raise ProxyError(f"Error requesting model: {e!r}", status.HTTP_502_BAD_GATEWAY) finally: await upstream_response.aclose() @@ -111,7 +111,7 @@ class _UpstreamStreamingResponse(StreamingResponse): including when the client disconnects before the stream starts. """ - def __init__(self, *args: Any, upstream_response: httpx.Response, **kwargs: Any) -> None: + def __init__(self, *args: Any, upstream_response: httpx2.Response, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._upstream_response = upstream_response @@ -220,7 +220,7 @@ def log_if_no_counts(self) -> None: async def _stream( - upstream_response: httpx.Response, + upstream_response: httpx2.Response, stream_options: ChatCompletionsStreamOptions, request_meter: _RequestMeter, ) -> AsyncIterator[bytes]: @@ -302,7 +302,7 @@ def is_complete() -> bool: else: # `rest` is not sent: it is a line that the service did not finish yield _get_error_event("the response ended before it was complete") - except httpx.RequestError as e: + except httpx2.RequestError as e: if not is_complete(): yield _get_error_event(repr(e)) diff --git a/src/dstack/_internal/proxy/lib/services/service_connection.py b/src/dstack/_internal/proxy/lib/services/service_connection.py index 56584941ee..96b71b5016 100644 --- a/src/dstack/_internal/proxy/lib/services/service_connection.py +++ b/src/dstack/_internal/proxy/lib/services/service_connection.py @@ -5,7 +5,7 @@ from tempfile import TemporaryDirectory from typing import Dict, Optional -import httpx2 as httpx +import httpx2 from httpx2 import AsyncHTTPTransport from dstack._internal.core.services.ssh.tunnel import ( @@ -36,13 +36,12 @@ REPLICA_DRAIN_TIMEOUT = 300 -class ServiceClient(httpx.AsyncClient): +class ServiceClient(httpx2.AsyncClient): """ - The client that the requests to a service share. An httpx2 client, since a request is - cancelled when its client disconnects, and httpx then leaves some connections unreleased. + The client that the requests to a service share. """ - def build_request(self, *args, **kwargs) -> httpx.Request: + def build_request(self, *args, **kwargs) -> httpx2.Request: self.cookies.clear() # the client is shared by all users, don't leak cookies return super().build_request(*args, **kwargs) @@ -304,7 +303,7 @@ def get_nginx_client(self, service: Service) -> ServiceClient: headers={"Host": domain}, timeout=service.read_timeout, # Each request in flight holds a connection, and their number is not limited. - limits=httpx.Limits(max_connections=None, max_keepalive_connections=20), + limits=httpx2.Limits(max_connections=None, max_keepalive_connections=20), ) return client @@ -316,7 +315,7 @@ async def remove_nginx_client(self, domain: str) -> None: async def get_service_replica_client( service: Service, repo: BaseProxyRepo, service_conn_pool: ServiceConnectionPool -) -> httpx.AsyncClient: +) -> httpx2.AsyncClient: """ `service` must have at least one replica """ diff --git a/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py b/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py index aabb244ce9..7ea770cc20 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py @@ -4,7 +4,7 @@ from datetime import timedelta from typing import Any, Awaitable, Callable, Optional, Sequence -from httpx import HTTPStatusError +from httpx2 import HTTPStatusError from sqlalchemy import and_, delete, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import ( diff --git a/src/dstack/_internal/server/background/scheduled_tasks/gateways.py b/src/dstack/_internal/server/background/scheduled_tasks/gateways.py index 4bcd90f42e..cbdb8a59b2 100644 --- a/src/dstack/_internal/server/background/scheduled_tasks/gateways.py +++ b/src/dstack/_internal/server/background/scheduled_tasks/gateways.py @@ -1,6 +1,6 @@ import asyncio -import httpx +import httpx2 from sqlalchemy import select from dstack._internal.core.errors import SSHError @@ -63,7 +63,7 @@ async def _process_connection(conn: GatewayConnection): try: await conn.try_collect_stats() - except httpx.HTTPError as e: + except httpx2.HTTPError as e: logger.warning("Failed to collect stats from gateway %s: %r", conn.ip_address, e) except Exception: logger.exception("Failed to collect stats from gateway %s", conn.ip_address) diff --git a/src/dstack/_internal/server/background/scheduled_tasks/probes.py b/src/dstack/_internal/server/background/scheduled_tasks/probes.py index 2d1821128b..69590d73d6 100644 --- a/src/dstack/_internal/server/background/scheduled_tasks/probes.py +++ b/src/dstack/_internal/server/background/scheduled_tasks/probes.py @@ -1,7 +1,7 @@ from datetime import timedelta from functools import partial -import httpx +import httpx2 from apscheduler.schedulers.asyncio import AsyncIOScheduler from sqlalchemy import select, update from sqlalchemy.orm import joinedload @@ -121,7 +121,7 @@ async def _execute_probe(probe: ProbeModel, probe_spec: ProbeSpec) -> bool: ) logger.debug("%s: probe status code: %s", fmt(probe), resp.status_code) return resp.is_success - except (SSHError, httpx.RequestError) as e: + except (SSHError, httpx2.RequestError) as e: logger.debug("%s: probe failed: %r", fmt(probe), e) return False diff --git a/src/dstack/_internal/server/services/gateways/__init__.py b/src/dstack/_internal/server/services/gateways/__init__.py index 0e6db3bf8d..26e25fa0f1 100644 --- a/src/dstack/_internal/server/services/gateways/__init__.py +++ b/src/dstack/_internal/server/services/gateways/__init__.py @@ -10,7 +10,7 @@ from datetime import timedelta from typing import List, Optional, Sequence -import httpx +import httpx2 from sqlalchemy import exists, func, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import joinedload, selectinload @@ -860,7 +860,7 @@ async def wait_for_gateway_replica_app( async with connection.client() as client: await client.info() break - except httpx.RequestError as e: + except httpx2.RequestError as e: logger.debug( "(attempt %s/%s) Gateway replica %s not yet available: %r", attempt + 1, diff --git a/src/dstack/_internal/server/services/gateways/client.py b/src/dstack/_internal/server/services/gateways/client.py index 799591c83a..f6570eaef0 100644 --- a/src/dstack/_internal/server/services/gateways/client.py +++ b/src/dstack/_internal/server/services/gateways/client.py @@ -2,7 +2,7 @@ import uuid from typing import Optional -import httpx +import httpx2 from pydantic import TypeAdapter from dstack._internal.core.consts import DSTACK_RUNNER_SSH_PORT @@ -46,7 +46,7 @@ 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 = AsyncClientWrapper( - transport=httpx.AsyncHTTPTransport(uds=uds) if uds else None, timeout=120 + transport=httpx2.AsyncHTTPTransport(uds=uds) if uds else None, timeout=120 ) async def register_service( @@ -321,7 +321,7 @@ def gateway_error(data: dict) -> GatewayError: return GatewayError(msg=data["detail"]) -class AsyncClientWrapper(httpx.AsyncClient): +class AsyncClientWrapper(httpx2.AsyncClient): 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 ec63ae8689..eebe97887d 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,7 +4,7 @@ from contextlib import asynccontextmanager from pathlib import Path -from httpx import AsyncClient, AsyncHTTPTransport +from httpx2 import AsyncClient, AsyncHTTPTransport from dstack._internal.server.models import JobModel from dstack._internal.server.services.jobs.job_replica_tunnel import get_service_replica_tunnel diff --git a/src/dstack/_internal/server/services/jobs/server_connection.py b/src/dstack/_internal/server/services/jobs/server_connection.py index 047a53ffa7..10646979bc 100644 --- a/src/dstack/_internal/server/services/jobs/server_connection.py +++ b/src/dstack/_internal/server/services/jobs/server_connection.py @@ -7,7 +7,7 @@ from typing import Optional from weakref import WeakValueDictionary -import httpx +import httpx2 from dstack._internal.core.consts import DSTACK_RUN_SERVER_SOCKET_PATH from dstack._internal.core.errors import SSHError @@ -152,14 +152,14 @@ async def close(self) -> None: shutil.rmtree(self._connection_dir, ignore_errors=True) async def _server_is_reachable(self) -> bool: - transport = httpx.AsyncHTTPTransport(uds=str(self._probe_socket_path)) + transport = httpx2.AsyncHTTPTransport(uds=str(self._probe_socket_path)) try: - async with httpx.AsyncClient( + async with httpx2.AsyncClient( transport=transport, timeout=_PROBE_TIMEOUT, ) as client: response = await client.get("http://localhost/healthcheck") - except httpx.HTTPError: + except httpx2.HTTPError: return False return response.status_code == 200 diff --git a/src/dstack/_internal/server/services/logs/fluentbit.py b/src/dstack/_internal/server/services/logs/fluentbit.py index f49f56e9a2..ca8850ef57 100644 --- a/src/dstack/_internal/server/services/logs/fluentbit.py +++ b/src/dstack/_internal/server/services/logs/fluentbit.py @@ -1,7 +1,7 @@ from typing import List, Optional, Protocol from uuid import UUID -import httpx +import httpx2 from dstack._internal.core.errors import ServerClientError from dstack._internal.core.models.logs import ( @@ -163,7 +163,7 @@ class HTTPFluentBitWriter: def __init__(self, host: str, port: int, tag_prefix: str) -> None: self._endpoint = f"http://{host}:{port}" - self._client = httpx.Client(timeout=30.0) + self._client = httpx2.Client(timeout=30.0) self._tag_prefix = tag_prefix def write(self, tag: str, records: List[dict]) -> None: @@ -176,11 +176,11 @@ def write(self, tag: str, records: List[dict]) -> None: headers={"Content-Type": "application/json"}, ) response.raise_for_status() - except httpx.HTTPStatusError as e: + except httpx2.HTTPStatusError as e: raise LogStorageError( f"Fluent-bit HTTP error: status {e.response.status_code}" ) from e - except httpx.HTTPError as e: + except httpx2.HTTPError as e: raise LogStorageError(f"Fluent-bit HTTP error: {e}") from e def close(self) -> None: diff --git a/src/dstack/_internal/server/services/proxy/services/service_proxy.py b/src/dstack/_internal/server/services/proxy/services/service_proxy.py index 61d4e9378c..713464f915 100644 --- a/src/dstack/_internal/server/services/proxy/services/service_proxy.py +++ b/src/dstack/_internal/server/services/proxy/services/service_proxy.py @@ -1,7 +1,7 @@ from typing import AsyncGenerator, AsyncIterator, Optional import fastapi -import httpx2 as httpx +import httpx2 from fastapi import status from starlette.requests import ClientDisconnect @@ -60,11 +60,11 @@ async def proxy( try: upstream_response = await client.send(upstream_request, stream=True) - except httpx.RequestError as e: + except httpx2.RequestError as e: logger.debug( "Error requesting %s %s: %r", upstream_request.method, upstream_request.url, e ) - if isinstance(e, httpx.TimeoutException): + if isinstance(e, httpx2.TimeoutException): raise ProxyError("Timed out requesting upstream", status.HTTP_504_GATEWAY_TIMEOUT) raise ProxyError("Error requesting upstream", status.HTTP_502_BAD_GATEWAY) @@ -85,26 +85,26 @@ def _is_whitelisted_path(path: str, whitelisted_paths: tuple[str, ...]) -> bool: return False -def clean_response_headers(headers: httpx.Headers) -> httpx.Headers: - headers = httpx.Headers(headers) # copy +def clean_response_headers(headers: httpx2.Headers) -> httpx2.Headers: + headers = httpx2.Headers(headers) # copy for header in UVICORN_AUTOMATIC_HEADERS: if header in headers: del headers[header] return headers -async def stream_response(response: httpx.Response) -> AsyncGenerator[bytes, None]: +async def stream_response(response: httpx2.Response) -> AsyncGenerator[bytes, None]: try: async for chunk in response.aiter_raw(): yield chunk - except httpx.RequestError as e: + except httpx2.RequestError as e: logger.debug( "Error streaming response %s %s: %r", response.request.method, response.request.url, e ) try: await response.aclose() - except httpx.RequestError as e: + except httpx2.RequestError as e: logger.debug( "Error closing response %s %s: %r", response.request.method, @@ -114,9 +114,9 @@ async def stream_response(response: httpx.Response) -> AsyncGenerator[bytes, Non async def build_upstream_request( - downstream_request: fastapi.Request, path: str, client: httpx.AsyncClient -) -> httpx.Request: - url = httpx.URL(path=path, query=downstream_request.url.query.encode("utf-8")) + downstream_request: fastapi.Request, path: str, client: httpx2.AsyncClient +) -> httpx2.Request: + url = httpx2.URL(path=path, query=downstream_request.url.query.encode("utf-8")) request_stream = await FastAPIToHttpxRequestStreamAdaptor( downstream_request.stream(), downstream_request.url ).get_stream() @@ -131,8 +131,8 @@ async def build_upstream_request( class FastAPIToHttpxRequestStreamAdaptor: """ If a FastAPI request has no body, its stream consists of empty byte sequences (b""). - This adaptor detects such streams and replaces them with None, otherwise httpx will - considers them actual request bodies, which can lead to unexpected behavior. + This adaptor detects such streams and replaces them with None, otherwise httpx2 will + consider them actual request bodies, which can lead to unexpected behavior. """ def __init__(self, stream: AsyncIterator[bytes], url: fastapi.datastructures.URL) -> None: diff --git a/src/dstack/_internal/server/services/runs/router_worker_sync.py b/src/dstack/_internal/server/services/runs/router_worker_sync.py index 65da86eedd..cb19081cb2 100644 --- a/src/dstack/_internal/server/services/runs/router_worker_sync.py +++ b/src/dstack/_internal/server/services/runs/router_worker_sync.py @@ -10,7 +10,7 @@ import grpc from google.protobuf.json_format import MessageToDict -from httpx import AsyncClient, RequestError, Response +from httpx2 import AsyncClient, RequestError, Response from pydantic import FailFast, Field, OnErrorOmit, TypeAdapter, ValidationError from smg_grpc_proto import ( sglang_scheduler_pb2, diff --git a/src/dstack/_internal/server/utils/otel/utils.py b/src/dstack/_internal/server/utils/otel/utils.py index 3f7f018187..d3a79ec8d3 100644 --- a/src/dstack/_internal/server/utils/otel/utils.py +++ b/src/dstack/_internal/server/utils/otel/utils.py @@ -7,7 +7,7 @@ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.exporter.prometheus import PrometheusMetricReader from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor -from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor +from opentelemetry.instrumentation.httpx import HTTPX2ClientInstrumentor from opentelemetry.instrumentation.requests import RequestsInstrumentor from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor @@ -83,7 +83,7 @@ def _instrument(app: FastAPI, engine: AsyncEngine) -> None: FastAPIInstrumentor.instrument_app(app) SQLAlchemyInstrumentor().instrument(engine=engine.sync_engine) _register_db_span_renaming(engine.sync_engine) - HTTPXClientInstrumentor().instrument() + 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. diff --git a/src/tests/_internal/proxy/gateway/routers/test_config.py b/src/tests/_internal/proxy/gateway/routers/test_config.py index 036489878e..5eece384bc 100644 --- a/src/tests/_internal/proxy/gateway/routers/test_config.py +++ b/src/tests/_internal/proxy/gateway/routers/test_config.py @@ -1,7 +1,7 @@ import signal from unittest.mock import Mock -import httpx +import httpx2 import pytest from dstack._internal.proxy.gateway.app import make_app @@ -10,9 +10,9 @@ from dstack._internal.proxy.gateway.routers import config -def make_client(repo: GatewayProxyRepo) -> httpx.AsyncClient: +def make_client(repo: GatewayProxyRepo) -> httpx2.AsyncClient: app = make_app(repo) - return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test/") + return httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url="http://test/") @pytest.mark.asyncio diff --git a/src/tests/_internal/proxy/gateway/routers/test_metering.py b/src/tests/_internal/proxy/gateway/routers/test_metering.py index ffea2ed1b9..61cc57a56a 100644 --- a/src/tests/_internal/proxy/gateway/routers/test_metering.py +++ b/src/tests/_internal/proxy/gateway/routers/test_metering.py @@ -2,7 +2,7 @@ from datetime import datetime, timezone from pathlib import Path -import httpx +import httpx2 import pytest import time_machine @@ -30,7 +30,7 @@ async def test_collect_metering(tmp_path: Path): ) await meter.flush() app = make_app(repo=GatewayProxyRepo(), meter=meter) - client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test/") + client = httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url="http://test/") resp = await client.post("/api/metering/collect", json={"after": 1, "limit": 10}) diff --git a/src/tests/_internal/proxy/gateway/routers/test_registry.py b/src/tests/_internal/proxy/gateway/routers/test_registry.py index d2a8330bc0..867292d5d0 100644 --- a/src/tests/_internal/proxy/gateway/routers/test_registry.py +++ b/src/tests/_internal/proxy/gateway/routers/test_registry.py @@ -6,7 +6,7 @@ from typing import Optional from unittest.mock import patch -import httpx +import httpx2 import pytest import time_machine @@ -23,10 +23,10 @@ from tests._internal.utils.test_ssh import PRIVATE_KEY, PUBLIC_KEY -def make_client(nginx_dir: Path, repo: Optional[GatewayProxyRepo] = None) -> httpx.AsyncClient: +def make_client(nginx_dir: Path, repo: Optional[GatewayProxyRepo] = None) -> httpx2.AsyncClient: (nginx_dir / "sites-enabled").mkdir(exist_ok=True) app = make_app(repo=repo or GatewayProxyRepo(), nginx=Nginx(nginx_dir=nginx_dir)) - return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test/") + return httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url="http://test/") def register_service_payload( diff --git a/src/tests/_internal/proxy/gateway/routers/test_services.py b/src/tests/_internal/proxy/gateway/routers/test_services.py index ade75946ab..5386e854d9 100644 --- a/src/tests/_internal/proxy/gateway/routers/test_services.py +++ b/src/tests/_internal/proxy/gateway/routers/test_services.py @@ -1,7 +1,7 @@ import threading import uuid -import httpx +import httpx2 import pytest from dstack._internal.proxy.gateway.app import make_app @@ -11,9 +11,9 @@ from dstack._internal.utils import ssh as ssh_utils -def make_client(repo: GatewayProxyRepo) -> httpx.AsyncClient: +def make_client(repo: GatewayProxyRepo) -> httpx2.AsyncClient: app = make_app(repo) - return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test/") + return httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url="http://test/") @pytest.mark.asyncio diff --git a/src/tests/_internal/proxy/gateway/routers/test_state.py b/src/tests/_internal/proxy/gateway/routers/test_state.py index 71ae1bb3ff..fdca38e151 100644 --- a/src/tests/_internal/proxy/gateway/routers/test_state.py +++ b/src/tests/_internal/proxy/gateway/routers/test_state.py @@ -1,4 +1,4 @@ -import httpx +import httpx2 import pytest from dstack._internal.proxy.gateway.app import make_app @@ -7,9 +7,9 @@ from dstack._internal.proxy.lib.testing.common import make_project, make_service -def make_client(repo: GatewayProxyRepo) -> httpx.AsyncClient: +def make_client(repo: GatewayProxyRepo) -> httpx2.AsyncClient: app = make_app(repo) - return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test/") + return httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url="http://test/") @pytest.mark.asyncio diff --git a/src/tests/_internal/proxy/gateway/routers/test_stats.py b/src/tests/_internal/proxy/gateway/routers/test_stats.py index 669b9f8394..ce68eac77e 100644 --- a/src/tests/_internal/proxy/gateway/routers/test_stats.py +++ b/src/tests/_internal/proxy/gateway/routers/test_stats.py @@ -1,7 +1,7 @@ from collections.abc import Iterable from unittest.mock import patch -import httpx +import httpx2 import pytest from dstack._internal.proxy.gateway.app import make_app @@ -10,9 +10,9 @@ from dstack._internal.proxy.lib.testing.common import make_project, make_service -def make_client(repo: GatewayProxyRepo) -> httpx.AsyncClient: +def make_client(repo: GatewayProxyRepo) -> httpx2.AsyncClient: app = make_app(repo) - return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test/") + return httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url="http://test/") @pytest.mark.asyncio 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 78aa71ff0f..9c335b8f01 100644 --- a/src/tests/_internal/proxy/gateway/services/test_server_client.py +++ b/src/tests/_internal/proxy/gateway/services/test_server_client.py @@ -4,7 +4,7 @@ from typing import cast import httpcore2 as httpcore -import httpx2 as httpx +import httpx2 import pytest from httpcore2._async.connection_pool import AsyncPoolRequest @@ -20,7 +20,7 @@ async def test_recovers_after_cancelled_pool_waiter(self, tmp_path, monkeypatch, (tmp_path / "server.sock").touch() client = HTTPMultiClient(tmp_path) cached = next(client._iter_clients_rand()) - pool = cast(httpx.AsyncHTTPTransport, cached.client._transport)._pool + pool = cast(httpx2.AsyncHTTPTransport, cached.client._transport)._pool assert isinstance(pool, httpcore.AsyncConnectionPool) pool._max_connections = 1 # Closing the first response assigns a fresh connection to the queued request. @@ -53,7 +53,7 @@ async def wait(self, timeout=None): if failure == "cancel": second.cancel() with pytest.raises( - asyncio.CancelledError if failure == "cancel" else httpx.RequestError + asyncio.CancelledError if failure == "cancel" else httpx2.RequestError ): await second @@ -81,18 +81,18 @@ async def test_failover_preserves_http_responses(self, tmp_path, monkeypatch, ou def first(request): requests.append("first") if outcome == "connect_error": - raise httpx.ConnectError("disconnected", request=request) + raise httpx2.ConnectError("disconnected", request=request) if outcome == "timeout": - raise httpx.PoolTimeout("busy", request=request) - return httpx.Response(403) + raise httpx2.PoolTimeout("busy", request=request) + return httpx2.Response(403) def second(request): requests.append("second") - return httpx.Response(200) + return httpx2.Response(200) for info, handler in zip(cached, (first, second)): await info.client.aclose() - info.client = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + info.client = httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) try: response = await client.post("/api/projects/test/get") assert response.status_code == (403 if outcome == "forbidden" else 200) diff --git a/src/tests/_internal/proxy/gateway/test_auth.py b/src/tests/_internal/proxy/gateway/test_auth.py index 738d2da719..b904c8534a 100644 --- a/src/tests/_internal/proxy/gateway/test_auth.py +++ b/src/tests/_internal/proxy/gateway/test_auth.py @@ -2,7 +2,7 @@ from typing import Optional from unittest.mock import AsyncMock -import httpx2 as httpx +import httpx2 import pytest import pytest_asyncio from aiocache.base import BaseCache @@ -65,13 +65,13 @@ async def test_caches_project_token_decision_for_sixty_seconds(self, monkeypatch def handle(request): requests.append(request) - return httpx.Response(status, content=make_project().model_dump_json()) + return httpx2.Response(status, content=make_project().model_dump_json()) cache = _get_auth_cache() set_value = AsyncMock(wraps=cache.set) monkeypatch.setattr(cache, "set", set_value) - async with httpx.AsyncClient( - transport=httpx.MockTransport(handle), base_url="http://dstack/" + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(handle), base_url="http://dstack/" ) as client: provider = GatewayProxyAuthProvider(client) for _ in range(2): @@ -87,7 +87,7 @@ def handle(request): await provider.is_project_member("second", "token") assert len(requests) == 3 - @pytest.mark.parametrize("failure", [500, httpx.ReadTimeout]) + @pytest.mark.parametrize("failure", [500, httpx2.ReadTimeout]) async def test_httpx2_failures_are_wrapped_and_not_cached(self, failure): requests = 0 @@ -95,18 +95,18 @@ def handle(request): nonlocal requests requests += 1 if requests > 1: - return httpx.Response(200, content=make_project().model_dump_json()) + return httpx2.Response(200, content=make_project().model_dump_json()) if isinstance(failure, int): - return httpx.Response(failure) + return httpx2.Response(failure) raise failure("temporary failure", request=request) - async with httpx.AsyncClient( - transport=httpx.MockTransport(handle), base_url="http://dstack/" + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(handle), base_url="http://dstack/" ) as client: provider = GatewayProxyAuthProvider(client) with pytest.raises(UnexpectedProxyError) as exc: await provider.is_project_member("test", "token") - assert isinstance(exc.value.__cause__, httpx.HTTPError) + assert isinstance(exc.value.__cause__, httpx2.HTTPError) assert await provider.is_project_member("test", "token") assert requests == 2 @@ -115,7 +115,7 @@ async def test_no_servers_reaches_auth_error_boundary(self, tmp_path): provider = GatewayProxyAuthProvider(client) with pytest.raises(UnexpectedProxyError) as exc: await provider.is_project_member("test", "token") - assert isinstance(exc.value.__cause__, httpx.RequestError) + assert isinstance(exc.value.__cause__, httpx2.RequestError) assert exc.value.__cause__.request.url.path == "/api/projects/test/get" @pytest.mark.parametrize( @@ -135,13 +135,13 @@ async def test_get_caller_allows_members_and_global_admins( def handle(request): if request.url.path == "/api/projects/test/get": - return httpx.Response(200, content=project.model_dump_json()) + return httpx2.Response(200, content=project.model_dump_json()) assert request.url.path == "/api/users/get_my_user" assert request.headers["Authorization"] == "Bearer token" - return httpx.Response(200, content=user.model_dump_json()) + return httpx2.Response(200, content=user.model_dump_json()) - async with httpx.AsyncClient( - transport=httpx.MockTransport(handle), base_url="http://dstack/" + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(handle), base_url="http://dstack/" ) as client: caller = await GatewayProxyAuthProvider(client).get_caller("test", "token") expected = ProxyCaller(project_id=project.project_id, user_id=user.id) @@ -153,11 +153,11 @@ async def test_get_caller_rechecks_global_admin_role(self): def handle(request): if request.url.path == "/api/users/get_my_user": - return httpx.Response(200, content=user.model_dump_json()) - return httpx.Response(200, content=project.model_dump_json()) + return httpx2.Response(200, content=user.model_dump_json()) + return httpx2.Response(200, content=project.model_dump_json()) - async with httpx.AsyncClient( - transport=httpx.MockTransport(handle), base_url="http://dstack/" + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(handle), base_url="http://dstack/" ) as client: provider = GatewayProxyAuthProvider(client) assert await provider.get_caller("test", "token") is not None @@ -171,15 +171,15 @@ async def test_parses_only_fields_needed_for_access_checks(self): project = make_project().model_dump(mode="json") project["members"][0]["project_role"] = "new-role" project["new_field"] = "new-value" - async with httpx.AsyncClient( - transport=httpx.MockTransport(lambda request: httpx.Response(200, json=project)), + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(lambda request: httpx2.Response(200, json=project)), base_url="http://dstack/", ) as client: assert await GatewayProxyAuthProvider(client).is_project_member("test", "token") async def test_get_caller_denies_if_server_denies(self): - async with httpx.AsyncClient( - transport=httpx.MockTransport(lambda request: httpx.Response(403)), + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(lambda request: httpx2.Response(403)), base_url="http://dstack/", ) as client: assert await GatewayProxyAuthProvider(client).get_caller("test", "token") is None @@ -190,10 +190,10 @@ async def test_get_caller_raises_not_found_if_project_does_not_exist(self): def handle(request): nonlocal requests requests += 1 - return httpx.Response(404) + return httpx2.Response(404) - async with httpx.AsyncClient( - transport=httpx.MockTransport(handle), base_url="http://dstack/" + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(handle), base_url="http://dstack/" ) as client: provider = GatewayProxyAuthProvider(client) for _ in range(2): @@ -207,10 +207,10 @@ async def test_quotes_project_name_in_server_request(self): def handle(request): paths.append(request.url.raw_path) - return httpx.Response(404) + return httpx2.Response(404) - async with httpx.AsyncClient( - transport=httpx.MockTransport(handle), base_url="http://dstack/" + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(handle), base_url="http://dstack/" ) as client: with pytest.raises(ProxyError): await GatewayProxyAuthProvider(client).get_caller("list?", "token") @@ -224,11 +224,11 @@ async def test_get_caller_requests_user_once_per_token(self): def handle(request): paths.append(request.url.path) if request.url.path == "/api/users/get_my_user": - return httpx.Response(200, content=user.model_dump_json()) - return httpx.Response(200, content=project.model_dump_json()) + return httpx2.Response(200, content=user.model_dump_json()) + return httpx2.Response(200, content=project.model_dump_json()) - async with httpx.AsyncClient( - transport=httpx.MockTransport(handle), base_url="http://dstack/" + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(handle), base_url="http://dstack/" ) as client: provider = GatewayProxyAuthProvider(client) for project_name in ("first", "second", "first"): diff --git a/src/tests/_internal/proxy/lib/routers/test_model_proxy.py b/src/tests/_internal/proxy/lib/routers/test_model_proxy.py index 4fdf93e605..8d0ae172dd 100644 --- a/src/tests/_internal/proxy/lib/routers/test_model_proxy.py +++ b/src/tests/_internal/proxy/lib/routers/test_model_proxy.py @@ -5,7 +5,7 @@ from typing import Any, AsyncIterator, Callable, Generator, Optional from unittest.mock import patch -import httpx2 as httpx +import httpx2 import openai import pytest from fastapi import FastAPI @@ -119,8 +119,8 @@ def make_app( def make_http_client( repo: BaseProxyRepo, auth: BaseProxyAuthProvider, meter: Optional[ProxyTestMeter] = None -) -> httpx.AsyncClient: - return httpx.AsyncClient(transport=httpx.ASGITransport(app=make_app(repo, auth, meter))) +) -> httpx2.AsyncClient: + return httpx2.AsyncClient(transport=httpx2.ASGITransport(app=make_app(repo, auth, meter))) def make_openai_client( @@ -308,7 +308,7 @@ async def test_unauthorized_http(headers) -> None: CHAT_COMPLETIONS_URL = "http://test-host/proxy/models/test-proj/chat/completions" AUTH_HEADERS = {"Authorization": "Bearer token"} -ServiceHandler = Callable[[httpx.Request], Any] +ServiceHandler = Callable[[httpx2.Request], Any] @pytest.fixture @@ -316,9 +316,9 @@ def mock_service() -> Generator[Callable[[ServiceHandler], None], None, None]: """Routes the requests that the proxy sends to the service to the given handler.""" handlers: list[ServiceHandler] = [] - async def get_service_replica_client(*args, **kwargs) -> httpx.AsyncClient: - return httpx.AsyncClient( - transport=httpx.MockTransport(handlers[0]), base_url="http://test-service" + async def get_service_replica_client(*args, **kwargs) -> httpx2.AsyncClient: + return httpx2.AsyncClient( + transport=httpx2.MockTransport(handlers[0]), base_url="http://test-service" ) with patch( @@ -391,9 +391,9 @@ async def test_forwards_request_and_response_unchanged(self, mock_service) -> No ) requests = [] - def handle(request: httpx.Request) -> httpx.Response: + def handle(request: httpx2.Request) -> httpx2.Response: requests.append(request) - return httpx.Response( + return httpx2.Response( 200, content=response_body, headers={"content-type": "application/json"} ) @@ -425,7 +425,7 @@ def handle(request: httpx.Request) -> httpx.Response: async def test_passes_service_errors_through(self, mock_service) -> None: error = b'{"error": {"message": "Too many requests"}}' mock_service( - lambda request: httpx.Response(429, content=error, headers={"Retry-After": "7"}) + lambda request: httpx2.Response(429, content=error, headers={"Retry-After": "7"}) ) auth = ProxyTestAuthProvider({"test-proj": {"token"}}) meter = ProxyTestMeter() @@ -444,7 +444,7 @@ async def test_json_response_to_stream_request_is_not_a_stream(self, mock_servic # A service that ignores `stream` response_body = json.dumps({"id": "1", "choices": [], "usage": usage(9, 2)}).encode() mock_service( - lambda request: httpx.Response( + lambda request: httpx2.Response( 200, content=response_body, headers={"content-type": "application/json"} ) ) @@ -460,7 +460,7 @@ async def test_json_response_to_stream_request_is_not_a_stream(self, mock_servic async def test_does_not_meter_token_counts_that_are_not_real(self, mock_service) -> None: response_body = b'{"choices": [], "usage": {"prompt_tokens": 9223372036854775808}}' - mock_service(lambda request: httpx.Response(200, content=response_body)) + mock_service(lambda request: httpx2.Response(200, content=response_body)) auth = ProxyTestAuthProvider({"test-proj": {"token"}}) meter = ProxyTestMeter() client = make_http_client(await make_repo(), auth, meter) @@ -492,9 +492,9 @@ async def test_stream_has_only_usage_that_client_asked_for( ) -> None: requests = [] - def handle(request: httpx.Request) -> httpx.Response: + def handle(request: httpx2.Request) -> httpx2.Response: requests.append(request) - return httpx.Response( + return httpx2.Response( 200, content=sse( chunk("Hello", usage(9, 1)), @@ -534,7 +534,7 @@ async def test_stream_has_last_usage_that_service_sent_with_choices( ) -> None: # Dynamo sends the last `usage` in the last chunk with choices mock_service( - lambda request: httpx.Response( + lambda request: httpx2.Response( 200, content=sse(chunk("Hello", usage(9, 1)), chunk(" there", usage(9, 2, 4))) ) ) @@ -557,7 +557,7 @@ async def test_stream_has_chunk_without_choices_and_usage(self, mock_service) -> # SGLang sends its `sglext` in such a chunk sglext = {"cached_tokens_details": {"device": 4}} mock_service( - lambda request: httpx.Response( + lambda request: httpx2.Response( 200, content=sse( chunk("Hello", usage(9, 1)), @@ -603,7 +603,7 @@ async def test_stream_has_chunk_without_choices_and_usage(self, mock_service) -> ), pytest.param( b"", - httpx.ReadError("broken"), + httpx2.ReadError("broken"), [], "Error requesting model: ReadError('broken')", id="read-error", @@ -623,7 +623,7 @@ async def stream() -> AsyncIterator[bytes]: if error is not None: raise error - mock_service(lambda request: httpx.Response(200, content=stream())) + mock_service(lambda request: httpx2.Response(200, content=stream())) auth = ProxyTestAuthProvider({"test-proj": {"token"}}) meter = ProxyTestMeter() repo = await make_repo() @@ -648,7 +648,7 @@ async def stream() -> AsyncIterator[bytes]: pass @pytest.mark.parametrize( - "error", [None, httpx.ReadError("broken")], ids=["service-closes-stream", "read-error"] + "error", [None, httpx2.ReadError("broken")], ids=["service-closes-stream", "read-error"] ) async def test_stream_without_done_is_complete_if_choices_are_finished( self, mock_service, error: Optional[Exception] @@ -660,7 +660,7 @@ async def stream() -> AsyncIterator[bytes]: if error is not None: raise error - mock_service(lambda request: httpx.Response(200, content=stream())) + mock_service(lambda request: httpx2.Response(200, content=stream())) auth = ProxyTestAuthProvider({"test-proj": {"token"}}) client = make_http_client(await make_repo(), auth, ProxyTestMeter()) request_body = {"model": "test-model", "messages": [], "stream": True} @@ -679,7 +679,7 @@ async def stream() -> AsyncIterator[bytes]: finally: is_stream_closed.set() - mock_service(lambda request: httpx.Response(200, content=stream())) + mock_service(lambda request: httpx2.Response(200, content=stream())) meter = ProxyTestMeter() request = ASGIRequest( make_app(await make_repo(), ProxyTestAuthProvider({"test-proj": {"token"}}), meter), @@ -699,7 +699,7 @@ async def test_does_not_meter_request_stopped_before_response( is_request_received = asyncio.Event() is_request_cancelled = asyncio.Event() - async def handle(request: httpx.Request) -> httpx.Response: + async def handle(request: httpx2.Request) -> httpx2.Response: is_request_received.set() try: await asyncio.Event().wait() # the model is generating @@ -724,7 +724,7 @@ async def handle(request: httpx.Request) -> httpx.Response: @pytest.mark.asyncio async def test_imported_model_is_served_to_importer_project_members_only(mock_service) -> None: - mock_service(lambda request: httpx.Response(200, json={"usage": usage(9, 2)})) + mock_service(lambda request: httpx2.Response(200, json={"usage": usage(9, 2)})) auth = ProxyTestAuthProvider( {"importer-proj": {"importer-token"}, "exporter-proj": {"exporter-token"}} ) diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py b/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py index 470d86bd80..dd0a8c62d4 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py @@ -6,7 +6,7 @@ from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patch import pytest -from httpx import HTTPStatusError, Request, Response +from httpx2 import HTTPStatusError, Request, Response from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/conftest.py b/src/tests/_internal/server/conftest.py index 9459c377c4..9e9f373011 100644 --- a/src/tests/_internal/server/conftest.py +++ b/src/tests/_internal/server/conftest.py @@ -3,7 +3,7 @@ from unittest.mock import AsyncMock, Mock, patch import gpuhunt -import httpx +import httpx2 import pytest from dstack._internal.server.main import app @@ -21,8 +21,8 @@ @pytest.fixture def client(): - transport = httpx.ASGITransport(app=app) - return httpx.AsyncClient(transport=transport, base_url="http://test") + transport = httpx2.ASGITransport(app=app) + return httpx2.AsyncClient(transport=transport, base_url="http://test") @pytest.fixture diff --git a/src/tests/_internal/server/routers/test_auth.py b/src/tests/_internal/server/routers/test_auth.py index f4c8bb0e59..e7ee9a7b97 100644 --- a/src/tests/_internal/server/routers/test_auth.py +++ b/src/tests/_internal/server/routers/test_auth.py @@ -2,7 +2,7 @@ from base64 import b64encode import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from dstack._internal.core.models.auth import OAuthProviderInfo from dstack._internal.server.services.auth import register_provider diff --git a/src/tests/_internal/server/routers/test_backends.py b/src/tests/_internal/server/routers/test_backends.py index f056dcc021..da51b84ebc 100644 --- a/src/tests/_internal/server/routers/test_backends.py +++ b/src/tests/_internal/server/routers/test_backends.py @@ -6,7 +6,7 @@ import pytest import yaml -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_events.py b/src/tests/_internal/server/routers/test_events.py index d27cfb9cb8..c3fc47262c 100644 --- a/src/tests/_internal/server/routers/test_events.py +++ b/src/tests/_internal/server/routers/test_events.py @@ -5,7 +5,7 @@ import pytest import pytest_asyncio import time_machine -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import delete from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_exports.py b/src/tests/_internal/server/routers/test_exports.py index a4a6a66c5c..19d7e14265 100644 --- a/src/tests/_internal/server/routers/test_exports.py +++ b/src/tests/_internal/server/routers/test_exports.py @@ -1,7 +1,7 @@ from typing import Optional import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_files.py b/src/tests/_internal/server/routers/test_files.py index c83938e71b..864a0a438b 100644 --- a/src/tests/_internal/server/routers/test_files.py +++ b/src/tests/_internal/server/routers/test_files.py @@ -1,7 +1,7 @@ from unittest.mock import AsyncMock, Mock import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_fleets.py b/src/tests/_internal/server/routers/test_fleets.py index 4b15b246d3..5c60cc39d0 100644 --- a/src/tests/_internal/server/routers/test_fleets.py +++ b/src/tests/_internal/server/routers/test_fleets.py @@ -6,7 +6,7 @@ import pytest import time_machine -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_gateways.py b/src/tests/_internal/server/routers/test_gateways.py index 2af2b335f6..dbd05a86af 100644 --- a/src/tests/_internal/server/routers/test_gateways.py +++ b/src/tests/_internal/server/routers/test_gateways.py @@ -2,7 +2,7 @@ from unittest.mock import patch import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.core.models.backends.base import BackendType diff --git a/src/tests/_internal/server/routers/test_gpus.py b/src/tests/_internal/server/routers/test_gpus.py index 8847b8031a..02f57e2c1e 100644 --- a/src/tests/_internal/server/routers/test_gpus.py +++ b/src/tests/_internal/server/routers/test_gpus.py @@ -4,7 +4,7 @@ import gpuhunt import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.core.models.backends.base import BackendType diff --git a/src/tests/_internal/server/routers/test_imports.py b/src/tests/_internal/server/routers/test_imports.py index fd43961b51..22483c77c5 100644 --- a/src/tests/_internal/server/routers/test_imports.py +++ b/src/tests/_internal/server/routers/test_imports.py @@ -1,7 +1,7 @@ from typing import Optional import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_instances.py b/src/tests/_internal/server/routers/test_instances.py index 43f0eb1c44..c4cc72b7fe 100644 --- a/src/tests/_internal/server/routers/test_instances.py +++ b/src/tests/_internal/server/routers/test_instances.py @@ -5,7 +5,7 @@ import pytest import pytest_asyncio -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_logs.py b/src/tests/_internal/server/routers/test_logs.py index 6c0d5e056c..e1359697a1 100644 --- a/src/tests/_internal/server/routers/test_logs.py +++ b/src/tests/_internal/server/routers/test_logs.py @@ -1,5 +1,5 @@ import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.core.models.users import GlobalRole, ProjectRole diff --git a/src/tests/_internal/server/routers/test_metrics.py b/src/tests/_internal/server/routers/test_metrics.py index d747c7ade7..dffb00ec22 100644 --- a/src/tests/_internal/server/routers/test_metrics.py +++ b/src/tests/_internal/server/routers/test_metrics.py @@ -1,7 +1,7 @@ from datetime import datetime, timezone import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.core.models.users import GlobalRole, ProjectRole diff --git a/src/tests/_internal/server/routers/test_projects.py b/src/tests/_internal/server/routers/test_projects.py index 37ec3ce835..4eeb19e497 100644 --- a/src/tests/_internal/server/routers/test_projects.py +++ b/src/tests/_internal/server/routers/test_projects.py @@ -4,7 +4,7 @@ import pytest import time_machine -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_prometheus.py b/src/tests/_internal/server/routers/test_prometheus.py index 26da89a90e..ded0197b27 100644 --- a/src/tests/_internal/server/routers/test_prometheus.py +++ b/src/tests/_internal/server/routers/test_prometheus.py @@ -4,7 +4,7 @@ from unittest.mock import patch import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.core.models.backends.base import BackendType diff --git a/src/tests/_internal/server/routers/test_public_keys.py b/src/tests/_internal/server/routers/test_public_keys.py index c344d9f13f..4abc9caa2f 100644 --- a/src/tests/_internal/server/routers/test_public_keys.py +++ b/src/tests/_internal/server/routers/test_public_keys.py @@ -4,7 +4,7 @@ import pytest import time_machine -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_repos.py b/src/tests/_internal/server/routers/test_repos.py index d85cd6635b..5c6eed9b77 100644 --- a/src/tests/_internal/server/routers/test_repos.py +++ b/src/tests/_internal/server/routers/test_repos.py @@ -2,7 +2,7 @@ from unittest.mock import AsyncMock, Mock import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_runs.py b/src/tests/_internal/server/routers/test_runs.py index a42c6c73e5..af61e0fd27 100644 --- a/src/tests/_internal/server/routers/test_runs.py +++ b/src/tests/_internal/server/routers/test_runs.py @@ -7,7 +7,7 @@ import pytest import time_machine -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_secrets.py b/src/tests/_internal/server/routers/test_secrets.py index cd486f536b..4f12c36dea 100644 --- a/src/tests/_internal/server/routers/test_secrets.py +++ b/src/tests/_internal/server/routers/test_secrets.py @@ -2,7 +2,7 @@ import pytest import time_machine -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_server.py b/src/tests/_internal/server/routers/test_server.py index 2178b44b84..fa22ce05d7 100644 --- a/src/tests/_internal/server/routers/test_server.py +++ b/src/tests/_internal/server/routers/test_server.py @@ -1,7 +1,7 @@ from unittest.mock import patch import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from dstack._internal import settings diff --git a/src/tests/_internal/server/routers/test_sshproxy.py b/src/tests/_internal/server/routers/test_sshproxy.py index 2b761b43f5..5295df7e9b 100644 --- a/src/tests/_internal/server/routers/test_sshproxy.py +++ b/src/tests/_internal/server/routers/test_sshproxy.py @@ -2,7 +2,7 @@ from typing import Optional import pytest -from httpx import AsyncClient +from httpx2 import AsyncClient from pytest_unordered import unordered from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_templates.py b/src/tests/_internal/server/routers/test_templates.py index 1e0d75f59b..a3c0aacbb7 100644 --- a/src/tests/_internal/server/routers/test_templates.py +++ b/src/tests/_internal/server/routers/test_templates.py @@ -4,7 +4,7 @@ import pytest import yaml from git import GitCommandError -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.core.models.users import GlobalRole, ProjectRole diff --git a/src/tests/_internal/server/routers/test_users.py b/src/tests/_internal/server/routers/test_users.py index b6c5c24485..e60c9eacaa 100644 --- a/src/tests/_internal/server/routers/test_users.py +++ b/src/tests/_internal/server/routers/test_users.py @@ -4,7 +4,7 @@ import pytest import time_machine -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/routers/test_volumes.py b/src/tests/_internal/server/routers/test_volumes.py index 30cab24233..6302e2b62a 100644 --- a/src/tests/_internal/server/routers/test_volumes.py +++ b/src/tests/_internal/server/routers/test_volumes.py @@ -5,7 +5,7 @@ import pytest import time_machine -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession diff --git a/src/tests/_internal/server/services/logs/test_fluentbit.py b/src/tests/_internal/server/services/logs/test_fluentbit.py index 3ace3bc68d..db8baec94c 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.httpx.Client") as mock: + with patch("dstack._internal.server.services.logs.fluentbit.httpx2.Client") as mock: yield mock.return_value def test_init_creates_client(self, mock_httpx_client): @@ -86,13 +86,13 @@ def test_write_calls_raise_for_status(self, mock_httpx_client): def test_write_raises_on_http_status_error(self, mock_httpx_client): """Test that 4xx/5xx responses are properly detected and raise LogStorageError.""" - import httpx + import httpx2 mock_response = Mock() mock_response.status_code = 500 mock_response.text = "Internal Server Error" mock_httpx_client.post.return_value = mock_response - mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( + mock_response.raise_for_status.side_effect = httpx2.HTTPStatusError( "Server Error", request=Mock(), response=mock_response ) writer = fluentbit.HTTPFluentBitWriter(host="localhost", port=8080, tag_prefix="dstack") @@ -101,9 +101,9 @@ def test_write_raises_on_http_status_error(self, mock_httpx_client): writer.write(tag="test-tag", records=[{"message": "test"}]) def test_write_raises_on_transport_error(self, mock_httpx_client): - import httpx + import httpx2 - mock_httpx_client.post.side_effect = httpx.HTTPError("Connection failed") + mock_httpx_client.post.side_effect = httpx2.HTTPError("Connection failed") writer = fluentbit.HTTPFluentBitWriter(host="localhost", port=8080, tag_prefix="dstack") with pytest.raises(LogStorageError, match="Fluent-bit HTTP error"): 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 b1c5fb3664..a9602f6893 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 @@ -1,7 +1,7 @@ from typing import Generator, Optional, Tuple from unittest.mock import patch -import httpx2 as httpx +import httpx2 import pytest from fastapi import FastAPI from fastapi.responses import PlainTextResponse @@ -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=httpx.ASGITransport(app)) + client = ServiceClient(base_url="http://test/", transport=httpx2.ASGITransport(app)) with patch( "dstack._internal.proxy.lib.services.service_connection.ServiceConnectionPool.get_or_add" ) as add_connection_mock: @@ -76,13 +76,13 @@ def make_app( return app -def make_client(app: FastAPI) -> httpx.AsyncClient: - return httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) +def make_client(app: FastAPI) -> httpx2.AsyncClient: + return httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app)) def make_app_client( repo: BaseProxyRepo = GatewayProxyRepo(), auth: BaseProxyAuthProvider = ProxyTestAuthProvider() -) -> Tuple[FastAPI, httpx.AsyncClient]: +) -> Tuple[FastAPI, httpx2.AsyncClient]: app = make_app(repo, auth) client = make_client(app) return app, client diff --git a/src/tests/_internal/server/services/runs/test_router_worker_sync.py b/src/tests/_internal/server/services/runs/test_router_worker_sync.py index f494592daa..971b608851 100644 --- a/src/tests/_internal/server/services/runs/test_router_worker_sync.py +++ b/src/tests/_internal/server/services/runs/test_router_worker_sync.py @@ -10,10 +10,10 @@ from unittest.mock import AsyncMock, patch import grpc -import httpx +import httpx2 import pytest from google.protobuf.message import Message -from httpx import AsyncClient +from httpx2 import AsyncClient from smg_grpc_proto import sglang_scheduler_pb2, vllm_engine_pb2 from sqlalchemy.ext.asyncio import AsyncSession @@ -346,7 +346,7 @@ async def test_cancels_pending_probes_after_success(self): async def test_failing_probe_does_not_hide_successful_one( self, caplog: pytest.LogCaptureFixture ): - def http_handler(request: httpx.Request) -> httpx.Response: + def http_handler(request: httpx2.Request) -> httpx2.Response: raise RuntimeError("boom") job = _job() @@ -494,7 +494,7 @@ async def test_returns_workers(self): "total": 2, "stats": {"prefill_count": 0, "decode_count": 0, "regular_count": 2}, } - async with _mock_client(lambda _: httpx.Response(200, json=payload)) as client: + async with _mock_client(lambda _: httpx2.Response(200, json=payload)) as client: assert await _get_router_workers(client, log_prefix="Router") == [ { "id": "1", @@ -505,37 +505,37 @@ async def test_returns_workers(self): ] async def test_returns_empty_list_when_router_has_no_workers(self): - async with _mock_client(lambda _: httpx.Response(200, json={"workers": []})) as client: + async with _mock_client(lambda _: httpx2.Response(200, json={"workers": []})) as client: assert await _get_router_workers(client, log_prefix="Router") == [] @pytest.mark.parametrize( "response", [ - pytest.param(httpx.Response(500, json={"workers": []}), id="unexpected-status"), - pytest.param(httpx.Response(200, content=b"not json"), id="unparsable"), - pytest.param(httpx.Response(200, json=["a"]), id="not-an-object"), - pytest.param(httpx.Response(200, json={}), id="no-workers"), - pytest.param(httpx.Response(200, json={"workers": "oops"}), id="not-an-array"), + pytest.param(httpx2.Response(500, json={"workers": []}), id="unexpected-status"), + pytest.param(httpx2.Response(200, content=b"not json"), id="unparsable"), + pytest.param(httpx2.Response(200, json=["a"]), id="not-an-object"), + pytest.param(httpx2.Response(200, json={}), id="no-workers"), + pytest.param(httpx2.Response(200, json={"workers": "oops"}), id="not-an-array"), pytest.param( - httpx.Response(200, json={"workers": [{"url": "http://10.0.0.1:8000"}]}), + httpx2.Response(200, json={"workers": [{"url": "http://10.0.0.1:8000"}]}), id="worker-without-id", ), pytest.param( - httpx.Response( + httpx2.Response( 200, json={"workers": [{"id": "1", "url": "http://10.0.0.1", "labels": {"a": 1}}]}, ), id="worker-with-invalid-labels", ), pytest.param( - httpx.Response( + httpx2.Response( 200, json={"workers": [{"id": str(i), "url": "u"} for i in range(8193)]} ), id="too-many-workers", ), ], ) - async def test_returns_none_on_unusable_response(self, response: httpx.Response): + async def test_returns_none_on_unusable_response(self, response: httpx2.Response): async with _mock_client(lambda _: response) as client: assert await _get_router_workers(client, log_prefix="Router") is None @@ -543,19 +543,19 @@ async def test_returns_none_on_unusable_response(self, response: httpx.Response) async def test_returns_none_when_response_too_large( self, caplog: pytest.LogCaptureFixture, with_content_length: bool ): - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: if with_content_length: - return httpx.Response(200, content=b" " * (2 * 1024 * 1024 + 1)) - return httpx.Response(200, content=_chunks(b" " * 1024 * 1024, count=3)) + return httpx2.Response(200, content=b" " * (2 * 1024 * 1024 + 1)) + return httpx2.Response(200, content=_chunks(b" " * 1024 * 1024, count=3)) async with _mock_client(handler) as client: assert await _get_router_workers(client, log_prefix="Router") is None assert "Router: GET /workers: response too large" in caplog.text async def test_returns_none_on_request_error(self, caplog: pytest.LogCaptureFixture): - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: # What an SSH tunnel to a port nobody listens on yet produces. - raise httpx.ReadError("") + raise httpx2.ReadError("") caplog.set_level(level=logging.DEBUG, logger=router_worker_sync.__name__) async with _mock_client(handler) as client: @@ -604,11 +604,11 @@ class TestAddWorkerToRouter: async def test_posts_worker_as_is( self, caplog: pytest.LogCaptureFixture, worker: _TargetWorker ): - requests: list[httpx.Request] = [] + requests: list[httpx2.Request] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: requests.append(request) - return httpx.Response(202, json={"status": "accepted", "worker_id": "1"}) + return httpx2.Response(202, json={"status": "accepted", "worker_id": "1"}) async with _mock_client(handler) as client: await _add_worker_to_router(client, log_prefix="Router", worker=worker) @@ -625,7 +625,7 @@ async def test_accepts_conflict_with_same_worker( ): # The router registers workers asynchronously, so a sync may add one again before # the router lists it - response = httpx.Response(409, json={"error": "conflict", "code": code}) + response = httpx2.Response(409, json={"error": "conflict", "code": code}) async with _mock_client(lambda _: response) as client: await _add_worker_to_router(client, log_prefix="Router", worker=_http_worker(0)) assert not [r for r in caplog.records if r.levelno > logging.DEBUG] @@ -634,34 +634,34 @@ async def test_accepts_conflict_with_same_worker( ["response", "message"], [ pytest.param( - httpx.Response(202, json={"status": "rejected", "worker_id": "1"}), + httpx2.Response(202, json={"status": "rejected", "worker_id": "1"}), "unexpected accepted status: rejected", id="not-accepted", ), pytest.param( - httpx.Response(202, json={"status": "accepted"}), + httpx2.Response(202, json={"status": "accepted"}), "accepted response validation failed", id="invalid-accepted", ), pytest.param( - httpx.Response(409, json={"error": "conflict", "code": "OTHER"}), + httpx2.Response(409, json={"error": "conflict", "code": "OTHER"}), "unexpected conflict code: OTHER", id="unexpected-conflict", ), pytest.param( - httpx.Response(409, json={}), + httpx2.Response(409, json={}), "conflict response validation failed", id="invalid-conflict", ), pytest.param( - httpx.Response(500, content=b"boom"), + httpx2.Response(500, content=b"boom"), "unexpected status code: 500: b'boom'", id="unexpected-status", ), ], ) async def test_warns_on_unexpected_response( - self, caplog: pytest.LogCaptureFixture, response: httpx.Response, message: str + self, caplog: pytest.LogCaptureFixture, response: httpx2.Response, message: str ): async with _mock_client(lambda _: response) as client: await _add_worker_to_router(client, log_prefix="Router", worker=_http_worker(0)) @@ -671,11 +671,11 @@ async def test_warns_on_unexpected_response( @pytest.mark.asyncio class TestRemoveWorkerFromRouter: async def test_deletes_worker_by_id(self, caplog: pytest.LogCaptureFixture): - requests: list[httpx.Request] = [] + requests: list[httpx2.Request] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: requests.append(request) - return httpx.Response(202, json={"status": "accepted", "worker_id": "w1"}) + return httpx2.Response(202, json={"status": "accepted", "worker_id": "w1"}) async with _mock_client(handler) as client: await _remove_worker_from_router(client, log_prefix="Router", worker_id="w1") @@ -686,7 +686,7 @@ def handler(request: httpx.Request) -> httpx.Response: async def test_logs_truncated_body_on_unexpected_status( self, caplog: pytest.LogCaptureFixture ): - response = httpx.Response(500, content=b"x" * 2000) + response = httpx2.Response(500, content=b"x" * 2000) async with _mock_client(lambda _: response) as client: await _remove_worker_from_router(client, log_prefix="Router", worker_id="w1") assert "Router: DELETE /workers/w1: unexpected status code: 500:" in caplog.text @@ -709,16 +709,16 @@ async def test_detects_sglang_worker(self): @pytest.mark.parametrize( "response", [ - pytest.param(httpx.Response(404), id="not-found"), - pytest.param(httpx.Response(200, content=b""), id="not-json"), - pytest.param(httpx.Response(200, json={"status": "ok"}), id="not-model-list"), - pytest.param(httpx.Response(200, json={"data": []}), id="no-models"), - pytest.param(httpx.Response(200, json={"data": [{"id": "m"}]}), id="no-owned-by"), - pytest.param(httpx.Response(200, content=b" " * (256 * 1024 + 1)), id="too-large"), + pytest.param(httpx2.Response(404), id="not-found"), + pytest.param(httpx2.Response(200, content=b""), id="not-json"), + pytest.param(httpx2.Response(200, json={"status": "ok"}), id="not-model-list"), + pytest.param(httpx2.Response(200, json={"data": []}), id="no-models"), + pytest.param(httpx2.Response(200, json={"data": [{"id": "m"}]}), id="no-owned-by"), + pytest.param(httpx2.Response(200, content=b" " * (256 * 1024 + 1)), id="too-large"), ], ) async def test_returns_none_quietly_when_not_worker( - self, caplog: pytest.LogCaptureFixture, response: httpx.Response + self, caplog: pytest.LogCaptureFixture, response: httpx2.Response ): caplog.set_level(level=logging.DEBUG, logger=router_worker_sync.__name__) async with _mock_client(lambda _: response) as client: @@ -748,24 +748,24 @@ async def test_returns_none_quietly_on_request_error(self, caplog: pytest.LogCap [ pytest.param( # A worker that requires an API key - httpx.Response(401), + httpx2.Response(401), "Worker: http://10.0.0.1:8000: GET /v1/models: unexpected status code: 401", id="unauthorized", ), pytest.param( - httpx.Response(200, json={"data": [{"owned_by": "vllm"}]}), + httpx2.Response(200, json={"data": [{"owned_by": "vllm"}]}), "Worker: http://10.0.0.1:8000: vllm: HTTP workers are not supported, use gRPC", id="vllm", ), pytest.param( - httpx.Response(200, json={"data": [{"owned_by": "tgi"}]}), + httpx2.Response(200, json={"data": [{"owned_by": "tgi"}]}), "Worker: http://10.0.0.1:8000: GET /v1/models: unsupported runtime: tgi", id="unsupported-runtime", ), ], ) async def test_warns_when_worker_not_supported( - self, caplog: pytest.LogCaptureFixture, response: httpx.Response, message: str + self, caplog: pytest.LogCaptureFixture, response: httpx2.Response, message: str ): async with _mock_client(lambda _: response) as client: assert ( @@ -807,7 +807,7 @@ class TestProbeSglangHttpWorker: ], ) async def test_reports_worker(self, server_info: dict, expected: dict): - async with _mock_client(lambda _: httpx.Response(200, json=server_info)) as client: + async with _mock_client(lambda _: httpx2.Response(200, json=server_info)) as client: worker = await _probe_sglang_http_worker( client, log_prefix="Worker", address="10.0.0.1:8000" ) @@ -820,10 +820,10 @@ async def test_reports_worker(self, server_info: dict, expected: dict): async def test_falls_back_to_deprecated_endpoint(self): # SGLang < 0.5.6 - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: if request.url.path == "/get_server_info": - return httpx.Response(200, json={"status": "ready"}) - return httpx.Response(404) + return httpx2.Response(200, json={"status": "ready"}) + return httpx2.Response(404) async with _mock_client(handler) as client: worker = await _probe_sglang_http_worker( @@ -837,7 +837,7 @@ def handler(request: httpx.Request) -> httpx.Response: } async def test_returns_none_when_not_ready(self, caplog: pytest.LogCaptureFixture): - response = httpx.Response(200, json={"status": "starting"}) + response = httpx2.Response(200, json={"status": "starting"}) async with _mock_client(lambda _: response) as client: assert ( await _probe_sglang_http_worker( @@ -876,7 +876,7 @@ async def test_returns_none_when_not_ready(self, caplog: pytest.LogCaptureFixtur async def test_returns_none_on_invalid_body( self, caplog: pytest.LogCaptureFixture, body: bytes ): - async with _mock_client(lambda _: httpx.Response(200, content=body)) as client: + async with _mock_client(lambda _: httpx2.Response(200, content=body)) as client: assert ( await _probe_sglang_http_worker( client, log_prefix="Worker", address="10.0.0.1:8000" @@ -898,7 +898,7 @@ async def test_returns_none_on_invalid_body( async def test_returns_none_on_unexpected_status( self, caplog: pytest.LogCaptureFixture, status_code: int, message: str ): - async with _mock_client(lambda _: httpx.Response(status_code)) as client: + async with _mock_client(lambda _: httpx2.Response(status_code)) as client: assert ( await _probe_sglang_http_worker( client, log_prefix="Worker", address="10.0.0.1:8000" @@ -908,8 +908,8 @@ async def test_returns_none_on_unexpected_status( assert f"Worker: http://10.0.0.1:8000: sglang: {message}" in caplog.text async def test_returns_none_on_request_error(self, caplog: pytest.LogCaptureFixture): - def handler(request: httpx.Request) -> httpx.Response: - raise httpx.ReadError("connection reset") + def handler(request: httpx2.Request) -> httpx2.Response: + raise httpx2.ReadError("connection reset") async with _mock_client(handler) as client: assert ( @@ -1230,9 +1230,9 @@ def __init__( self.added: list[dict] = [] self.removed_ids: list[str] = [] - def handle(self, request: httpx.Request) -> httpx.Response: + def handle(self, request: httpx2.Request) -> httpx2.Response: if request.method == "GET" and request.url.path == "/workers": - return httpx.Response(200, json={"workers": self.workers, "total": len(self.workers)}) + return httpx2.Response(200, json={"workers": self.workers, "total": len(self.workers)}) if self.update_error is not None: raise self.update_error if request.method == "POST" and request.url.path == "/workers": @@ -1240,13 +1240,13 @@ def handle(self, request: httpx.Request) -> httpx.Response: worker_id = f"added-{len(self.added)}" self.added.append(worker) self.workers.append({"id": worker_id, **worker}) - return httpx.Response(202, json={"status": "accepted", "worker_id": worker_id}) + return httpx2.Response(202, json={"status": "accepted", "worker_id": worker_id}) if request.method == "DELETE" and request.url.path.startswith("/workers/"): worker_id = request.url.path.removeprefix("/workers/") self.removed_ids.append(worker_id) self.workers = [w for w in self.workers if w["id"] != worker_id] - return httpx.Response(202, json={"status": "accepted", "worker_id": worker_id}) - return httpx.Response(404) + return httpx2.Response(202, json={"status": "accepted", "worker_id": worker_id}) + return httpx2.Response(404) @contextmanager @@ -1289,7 +1289,7 @@ def _job() -> JobModel: @contextmanager def _fake_replica_transports( *, - http_handler: Optional[Callable[[httpx.Request], httpx.Response]] = None, + http_handler: Optional[Callable[[httpx2.Request], httpx2.Response]] = None, grpc_channel: Optional["_FakeGrpcChannel"] = None, tunnel_error: Optional[Exception] = None, ) -> Iterator[None]: @@ -1324,22 +1324,22 @@ async def get_grpc_channel(uds_path: Path) -> AsyncIterator["_FakeGrpcChannel"]: yield -def _sglang_http_handler(server_info: dict) -> Callable[[httpx.Request], httpx.Response]: +def _sglang_http_handler(server_info: dict) -> Callable[[httpx2.Request], httpx2.Response]: """An SGLang HTTP worker replica that reports the given server info""" - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: if request.url.path == "/v1/models": - return httpx.Response(200, json={"data": [{"id": "model", "owned_by": "sglang"}]}) + return httpx2.Response(200, json={"data": [{"id": "model", "owned_by": "sglang"}]}) if request.url.path == "/server_info": - return httpx.Response(200, json=server_info) - return httpx.Response(404) + return httpx2.Response(200, json=server_info) + return httpx2.Response(404) return handler -def _grpc_server_http_handler(request: httpx.Request) -> httpx.Response: +def _grpc_server_http_handler(request: httpx2.Request) -> httpx2.Response: # What an HTTP/1.1 request to an HTTP/2-only gRPC server produces - raise httpx.RemoteProtocolError("illegal request line") + raise httpx2.RemoteProtocolError("illegal request line") def _fake_grpc_channel( @@ -1402,8 +1402,8 @@ def _rpc_error(code: grpc.StatusCode) -> grpc.aio.AioRpcError: return grpc.aio.AioRpcError(code, grpc.aio.Metadata(), grpc.aio.Metadata(), details=code.name) -def _mock_client(handler: Callable[[httpx.Request], httpx.Response]) -> AsyncClient: - return AsyncClient(transport=httpx.MockTransport(handler)) +def _mock_client(handler: Callable[[httpx2.Request], httpx2.Response]) -> AsyncClient: + return AsyncClient(transport=httpx2.MockTransport(handler)) async def _chunks(chunk: bytes, *, count: int) -> AsyncIterator[bytes]: diff --git a/src/tests/_internal/server/test_app.py b/src/tests/_internal/server/test_app.py index 6d6d7db01b..9e619d65bb 100644 --- a/src/tests/_internal/server/test_app.py +++ b/src/tests/_internal/server/test_app.py @@ -3,7 +3,7 @@ import pytest from fastapi.testclient import TestClient -from httpx import AsyncClient +from httpx2 import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal import settings From 3dc818f6877fab2a3841061e4426d091b0ac06d6 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 13:00:18 +0500 Subject: [PATCH 2/5] Fall back to certifi on Linux without system CA certificates --- pyproject.toml | 1 + .../core/backends/vastai/api_client.py | 2 + src/dstack/_internal/utils/tls.py | 61 ++++++++++ src/tests/_internal/utils/test_tls.py | 105 ++++++++++++++++++ 4 files changed, 169 insertions(+) create mode 100644 src/dstack/_internal/utils/tls.py create mode 100644 src/tests/_internal/utils/test_tls.py diff --git a/pyproject.toml b/pyproject.toml index ddd3962bf7..1d3aa07ab2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ "pyyaml", "requests", "requests-unixsocket>=0.4.1", + "certifi", "typing-extensions>=4.0.0", "cryptography", "packaging", diff --git a/src/dstack/_internal/core/backends/vastai/api_client.py b/src/dstack/_internal/core/backends/vastai/api_client.py index f59febcd80..c3015ed286 100644 --- a/src/dstack/_internal/core/backends/vastai/api_client.py +++ b/src/dstack/_internal/core/backends/vastai/api_client.py @@ -7,6 +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 class VastAIRateLimitError(Exception): @@ -36,6 +37,7 @@ def __init__(self, api_key: str): 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/utils/tls.py b/src/dstack/_internal/utils/tls.py new file mode 100644 index 0000000000..bfb84f334d --- /dev/null +++ b/src/dstack/_internal/utils/tls.py @@ -0,0 +1,61 @@ +import functools +import os +import platform +import re +import ssl + +import certifi +import httpx2 + +from dstack._internal.utils.logging import get_logger + +logger = get_logger(__name__) + + +def get_default_ssl_context() -> ssl.SSLContext: + """ + Returns a new SSL context to verify HTTPS servers with. It is the httpx2 default + (`SSL_CERT_FILE` / `SSL_CERT_DIR` if set, the OS verifier on macOS and Windows, + the system CA certificates on Linux), except on Linux systems without CA certificates, + such as containers from images without `ca-certificates`, where it trusts the certifi bundle. + + Give each client its own context: httpx2 modifies the context on every connection + (it sets the ALPN protocols from the client's HTTP/2 settings). + """ + if _should_use_certifi(): + return ssl.create_default_context(cafile=certifi.where()) + return httpx2.create_ssl_context() + + +@functools.cache +def _should_use_certifi() -> bool: + if ( + platform.system() != "Linux" + or os.environ.get("SSL_CERT_FILE") + or os.environ.get("SSL_CERT_DIR") + or _has_ca_certificates(httpx2.create_ssl_context()) + ): + return False + logger.warning( + "No system CA certificates found, using the certifi bundle." + " Install the ca-certificates package or set SSL_CERT_FILE=$(python -m certifi)." + ) + return True + + +def _has_ca_certificates(ctx: ssl.SSLContext) -> bool: + # Relies on httpx2 loading the CA file when it creates the context, so that the count + # reflects the system store it found. This holds for the stdlib `SSLContext` that httpx2 + # builds on Linux; it would not if loading were deferred to the first handshake. + if ctx.cert_store_stats()["x509_ca"] > 0: + return True + # Certificates from a CA directory are loaded on demand, so they are not counted above. + # E.g. uv-managed Python looks for /etc/ssl/cert.pem and /etc/ssl/certs, and Debian and + # Ubuntu provide only the latter. + return _has_hashed_certificates(ssl.get_default_verify_paths().openssl_capath) + + +def _has_hashed_certificates(capath: str) -> bool: + if not os.path.isdir(capath): + return False + return any(re.fullmatch(r"[0-9a-fA-F]{8}\.\d+", name) for name in os.listdir(capath)) diff --git a/src/tests/_internal/utils/test_tls.py b/src/tests/_internal/utils/test_tls.py new file mode 100644 index 0000000000..eecf9b3c97 --- /dev/null +++ b/src/tests/_internal/utils/test_tls.py @@ -0,0 +1,105 @@ +import logging +import ssl +from pathlib import Path + +import certifi +import pytest + +from dstack._internal.utils import tls +from dstack._internal.utils.tls import get_default_ssl_context + + +class TestGetDefaultSSLContext: + @pytest.fixture(autouse=True) + def clear_cache(self): + tls._should_use_certifi.cache_clear() + yield + tls._should_use_certifi.cache_clear() + + @pytest.fixture(autouse=True) + def linux(self, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(tls.platform, "system", lambda: "Linux") + monkeypatch.delenv("SSL_CERT_FILE", raising=False) + monkeypatch.delenv("SSL_CERT_DIR", raising=False) + + @pytest.fixture + def empty_context(self, monkeypatch: pytest.MonkeyPatch) -> ssl.SSLContext: + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + monkeypatch.setattr(tls.httpx2, "create_ssl_context", lambda: ctx) + return ctx + + def test_falls_back_to_certifi_without_system_store( + self, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + empty_context: ssl.SSLContext, + caplog: pytest.LogCaptureFixture, + ): + caplog.set_level(logging.WARNING) + self._set_openssl_capath(monkeypatch, tmp_path / "missing") + ctx = get_default_ssl_context() + assert ctx is not empty_context + assert ctx.verify_mode == ssl.CERT_REQUIRED + assert ctx.check_hostname + assert ctx.cert_store_stats()["x509_ca"] > 0 + assert "using the certifi bundle" in caplog.text + + def test_keeps_system_store_loaded_from_file(self, monkeypatch: pytest.MonkeyPatch): + system_ctx = ssl.create_default_context(cafile=certifi.where()) + monkeypatch.setattr(tls.httpx2, "create_ssl_context", lambda: system_ctx) + assert get_default_ssl_context() is system_ctx + + def test_keeps_system_store_loaded_from_directory( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, empty_context: ssl.SSLContext + ): + (tmp_path / "1a2b3c4d.0").touch() + self._set_openssl_capath(monkeypatch, tmp_path) + assert get_default_ssl_context() is empty_context + + def test_ignores_directory_without_hashed_certificates( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, empty_context: ssl.SSLContext + ): + (tmp_path / "ca-bundle.crt").touch() + self._set_openssl_capath(monkeypatch, tmp_path) + assert get_default_ssl_context() is not empty_context + + @pytest.mark.parametrize("env_var", ["SSL_CERT_FILE", "SSL_CERT_DIR"]) + def test_does_not_fall_back_with_explicit_store( + self, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + empty_context: ssl.SSLContext, + env_var: str, + ): + monkeypatch.setenv(env_var, str(tmp_path / "custom")) + self._set_openssl_capath(monkeypatch, tmp_path / "missing") + assert get_default_ssl_context() is empty_context + + @pytest.mark.parametrize("system", ["Darwin", "Windows"]) + def test_does_not_fall_back_outside_linux( + self, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + empty_context: ssl.SSLContext, + system: str, + ): + monkeypatch.setattr(tls.platform, "system", lambda: system) + self._set_openssl_capath(monkeypatch, tmp_path / "missing") + assert get_default_ssl_context() is empty_context + + @pytest.mark.parametrize("has_system_store", [True, False]) + def test_returns_new_context_on_each_call( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, has_system_store: bool + ): + monkeypatch.setattr( + tls.httpx2, "create_ssl_context", lambda: ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ) + if has_system_store: + (tmp_path / "1a2b3c4d.0").touch() + self._set_openssl_capath(monkeypatch, tmp_path) + assert get_default_ssl_context() is not get_default_ssl_context() + + @staticmethod + def _set_openssl_capath(monkeypatch: pytest.MonkeyPatch, capath: Path) -> None: + paths = ssl.DefaultVerifyPaths("", "", "SSL_CERT_FILE", "", "SSL_CERT_DIR", str(capath)) + monkeypatch.setattr(tls.ssl, "get_default_verify_paths", lambda: paths) From ef5d4b71d54c8eee8ad3749f996dfdc90d557190 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 13:49:01 +0500 Subject: [PATCH 3/5] Fall back to certifi on all platforms httpx2 doesn't send to truststore --- src/dstack/_internal/utils/tls.py | 8 +++++--- src/tests/_internal/utils/test_tls.py | 5 ++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/dstack/_internal/utils/tls.py b/src/dstack/_internal/utils/tls.py index bfb84f334d..826fd8b6f5 100644 --- a/src/dstack/_internal/utils/tls.py +++ b/src/dstack/_internal/utils/tls.py @@ -16,7 +16,7 @@ def get_default_ssl_context() -> ssl.SSLContext: """ Returns a new SSL context to verify HTTPS servers with. It is the httpx2 default (`SSL_CERT_FILE` / `SSL_CERT_DIR` if set, the OS verifier on macOS and Windows, - the system CA certificates on Linux), except on Linux systems without CA certificates, + the system CA certificates elsewhere), except on systems without CA certificates, such as containers from images without `ca-certificates`, where it trusts the certifi bundle. Give each client its own context: httpx2 modifies the context on every connection @@ -30,7 +30,8 @@ def get_default_ssl_context() -> ssl.SSLContext: @functools.cache def _should_use_certifi() -> bool: if ( - platform.system() != "Linux" + # httpx2 uses the OS verifier on these, which always has a store. + platform.system() in ("Windows", "Darwin") or os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR") or _has_ca_certificates(httpx2.create_ssl_context()) @@ -46,7 +47,8 @@ def _should_use_certifi() -> bool: def _has_ca_certificates(ctx: ssl.SSLContext) -> bool: # Relies on httpx2 loading the CA file when it creates the context, so that the count # reflects the system store it found. This holds for the stdlib `SSLContext` that httpx2 - # builds on Linux; it would not if loading were deferred to the first handshake. + # builds outside macOS and Windows; it would not if loading were deferred to the first + # handshake. if ctx.cert_store_stats()["x509_ca"] > 0: return True # Certificates from a CA directory are loaded on demand, so they are not counted above. diff --git a/src/tests/_internal/utils/test_tls.py b/src/tests/_internal/utils/test_tls.py index eecf9b3c97..3dd2a296c4 100644 --- a/src/tests/_internal/utils/test_tls.py +++ b/src/tests/_internal/utils/test_tls.py @@ -28,13 +28,16 @@ def empty_context(self, monkeypatch: pytest.MonkeyPatch) -> ssl.SSLContext: monkeypatch.setattr(tls.httpx2, "create_ssl_context", lambda: ctx) return ctx + @pytest.mark.parametrize("system", ["Linux", "FreeBSD"]) def test_falls_back_to_certifi_without_system_store( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, empty_context: ssl.SSLContext, caplog: pytest.LogCaptureFixture, + system: str, ): + monkeypatch.setattr(tls.platform, "system", lambda: system) caplog.set_level(logging.WARNING) self._set_openssl_capath(monkeypatch, tmp_path / "missing") ctx = get_default_ssl_context() @@ -76,7 +79,7 @@ def test_does_not_fall_back_with_explicit_store( assert get_default_ssl_context() is empty_context @pytest.mark.parametrize("system", ["Darwin", "Windows"]) - def test_does_not_fall_back_outside_linux( + def test_does_not_fall_back_on_macos_and_windows( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, From 32621240c7298b06f3e5f3a3f009c9b9ed8385f9 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 13:49:02 +0500 Subject: [PATCH 4/5] Make httpx2 a base dependency --- pyproject.toml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 1d3aa07ab2..522c0321cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ "pyyaml", "requests", "requests-unixsocket>=0.4.1", + "httpx2>=2.16.2", "certifi", "typing-extensions>=4.0.0", "cryptography", @@ -220,7 +221,6 @@ gateway = [ "uvloop>=0.18.0; sys_platform != 'win32' and platform_python_implementation != 'PyPy'", "aiorwlock", "aiocache", - "httpx2>=2.16.2", "jinja2", # Always installed so that OpenTelemetry can be enabled without reinstalling the gateway. "opentelemetry-sdk>=1.39.0", @@ -236,7 +236,6 @@ server = [ "uvicorn[standard]", "aiorwlock", "aiocache", - "httpx2>=2.16.2", "jinja2", "watchfiles", "sqlalchemy[asyncio]>=2.0.0", From 5130dd1b9d81aac45f3a28dac74e928278c6a04f Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Mon, 30 Nov 2026 14:23:22 +0500 Subject: [PATCH 5/5] Test certifi fallback detection against real httpx2 on Linux --- src/tests/_internal/utils/test_tls.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/tests/_internal/utils/test_tls.py b/src/tests/_internal/utils/test_tls.py index 3dd2a296c4..8e3135cc69 100644 --- a/src/tests/_internal/utils/test_tls.py +++ b/src/tests/_internal/utils/test_tls.py @@ -1,5 +1,6 @@ import logging import ssl +import sys from pathlib import Path import certifi @@ -102,6 +103,12 @@ def test_returns_new_context_on_each_call( self._set_openssl_capath(monkeypatch, tmp_path) assert get_default_ssl_context() is not get_default_ssl_context() + @pytest.mark.skipif(sys.platform != "linux", reason="httpx2 builds a stdlib context on Linux") + def test_keeps_system_store_of_real_httpx2_context(self): + # Assumes a host with system CA certificates, as CI runners have. Fails if httpx2 stops + # loading them when it creates the context, which the detection relies on. + assert not tls._should_use_certifi() + @staticmethod def _set_openssl_capath(monkeypatch: pytest.MonkeyPatch, capath: Path) -> None: paths = ssl.DefaultVerifyPaths("", "", "SSL_CERT_FILE", "", "SSL_CERT_DIR", str(capath))