Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ dependencies = [
"pyyaml",
"requests",
"requests-unixsocket>=0.4.1",
"httpx2>=2.16.2",
"certifi",
"typing-extensions>=4.0.0",
"cryptography",
"packaging",
Expand Down Expand Up @@ -219,10 +221,6 @@ 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",
"jinja2",
# Always installed so that OpenTelemetry can be enabled without reinstalling the gateway.
"opentelemetry-sdk>=1.39.0",
Expand All @@ -238,9 +236,6 @@ 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",
"jinja2",
"watchfiles",
"sqlalchemy[asyncio]>=2.0.0",
Expand Down Expand Up @@ -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",
Expand Down
8 changes: 5 additions & 3 deletions src/dstack/_internal/core/backends/vastai/api_client.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
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
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):
Expand All @@ -32,10 +33,11 @@ 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,
verify=get_default_ssl_context(),
)

def create_instance(
Expand Down Expand Up @@ -124,5 +126,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
14 changes: 7 additions & 7 deletions src/dstack/_internal/proxy/gateway/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand All @@ -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.
Expand All @@ -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
Expand Down
3 changes: 1 addition & 2 deletions src/dstack/_internal/proxy/gateway/otel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()

Expand Down
22 changes: 11 additions & 11 deletions src/dstack/_internal/proxy/gateway/services/server_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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: [])

Expand All @@ -26,21 +26,21 @@ 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):
super().__init__(base_url=BASE_URL)
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.
Expand All @@ -49,15 +49,15 @@ 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(
"Removing socket %s after several failed connection attempts",
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)

Expand All @@ -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"))
Expand All @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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()
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import httpx2 as httpx
import httpx2

from dstack._internal.proxy.lib.errors import UnexpectedProxyError
from dstack._internal.proxy.lib.models import ChatModel
from dstack._internal.proxy.lib.services.model_proxy.clients.base import ChatCompletionsClient
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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", "")
Expand All @@ -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()
Expand All @@ -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

Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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))

Expand Down
13 changes: 6 additions & 7 deletions src/dstack/_internal/proxy/lib/services/service_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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

Expand All @@ -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
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
Loading
Loading