Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
48c38a4
Add HTTPClient and AsyncHTTPClient with dstack defaults
r4victor Nov 30, 2026
4f17498
Add http_mock fixture for httpx2 clients
r4victor Nov 30, 2026
5e84ca1
Move runner and shim clients to httpx2
r4victor Nov 30, 2026
81f830d
Move backend API clients to httpx2
r4victor Nov 30, 2026
a469058
Move REST plugin and tokenizer config requests to httpx2
r4victor Nov 30, 2026
f6ad0b9
Move Python API and CLI to httpx2
r4victor Nov 30, 2026
4580708
Test APIClient URL without scheme without http_mock
r4victor Nov 30, 2026
5913532
Lower APIClient timeouts to 60s
r4victor Nov 30, 2026
e4bb97d
Require an explicit timeout for HTTP clients
r4victor Nov 30, 2026
d6dc7bb
Close gateway clients when closing gateway connections
r4victor Nov 30, 2026
8545a7b
Fix docstring
r4victor Nov 30, 2026
642dc47
Don't load CA certificates for plain HTTP clients
r4victor Nov 30, 2026
c84fe5a
Raise ClientError for unexpected 400 and 422 response bodies
r4victor Nov 30, 2026
9c154c7
Fix optional SSL context typing in test_http
r4victor Nov 30, 2026
9b3b3e0
Raise a resolve error for any request error in resolve_url
r4victor Nov 30, 2026
cb04a13
Treat non-UTF-8 CloudRift responses as non-JSON
r4victor Nov 30, 2026
147674c
Close gateway connections that fail to open
r4victor Nov 30, 2026
f1c537b
Report unexpected registry manifests as DockerRegistryError
r4victor Nov 30, 2026
ac1b383
Report only rejected Vast.ai keys as invalid credentials
r4victor Nov 30, 2026
9012ecf
Close evicted gateway server clients
r4victor Nov 30, 2026
67728c8
Add close() to APIClient and Client
r4victor Nov 30, 2026
c43d55b
Fix concurrent eviction of gateway server clients
r4victor Nov 30, 2026
d58eb2d
Keep replacement gateway connection when a failed open cleans up
r4victor Nov 30, 2026
0d8c255
Raise GatewayError when using a closed gateway connection
r4victor Nov 30, 2026
9d08986
Close evicted gateway server clients only when idle
r4victor Nov 30, 2026
185f21e
Add close() to Vast.ai API client and compute
r4victor Nov 30, 2026
7c34c66
Close backend API clients created for credentials validation
r4victor Nov 30, 2026
cbb4611
Report Vast.ai validation request failures as client errors
r4victor Nov 30, 2026
3928303
Close preset files response when iteration stops early
r4victor Nov 30, 2026
d664e9a
Drop redundant HTTP client tests
r4victor Nov 30, 2026
175a86e
Don't close a gateway connection again after it was removed while ope…
r4victor Nov 30, 2026
dece3d1
Don't reopen tunnels of closed gateway connections
r4victor Nov 30, 2026
a348e9f
Raise a resolve error for invalid URLs in resolve_url
r4victor Nov 30, 2026
e40784f
Fix preset files test for the closed response
r4victor Nov 30, 2026
0327ae9
Add contributing notes on HTTP requests
r4victor Nov 30, 2026
e224d5d
Mention HTTP clients in ARCHITECTURE.md instead of a separate doc
r4victor Nov 30, 2026
655bf06
Move the HTTP clients note to a Misc section
r4victor Nov 30, 2026
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
4 changes: 4 additions & 0 deletions contributing/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,7 @@ The server is a FastAPI app backend by SQLite or Postgres. The runner and shim a
* `openai/` - OpenAI API proxy
* `registry/` - gateway services registry
* `systemd/` - systemd service files

## Misc

* HTTP clients use [httpx2](https://github.com/pydantic/httpx2). Create them with `HTTPClient` and `AsyncHTTPClient` from `dstack._internal.utils.http`.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ classifiers = [
dependencies = [
"pyyaml",
"requests",
"requests-unixsocket>=0.4.1",
"httpx2>=2.16.2",
"certifi",
"typing-extensions>=4.0.0",
Expand Down
11 changes: 1 addition & 10 deletions src/dstack/_internal/cli/commands/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from typing import Optional

import questionary
from requests import HTTPError
from rich.table import Table

import dstack.api.server
Expand Down Expand Up @@ -138,15 +137,7 @@ def _command(self, args: argparse.Namespace):
def _add(self, args: argparse.Namespace):
config_manager = ConfigManager()
api_client = dstack.api.server.APIClient(base_url=args.url, token=args.token)
try:
api_client.projects.get(args.name)
except HTTPError as e:
if e.response is not None and e.response.status_code == 403:
raise CLIError("Forbidden. Ensure the token is valid.")
elif e.response is not None and e.response.status_code == 404:
raise CLIError(f"Project '{args.name}' not found.")
else:
raise e
api_client.projects.get(args.name)
default_project = config_manager.get_project_config()
if (
default_project is None
Expand Down
14 changes: 6 additions & 8 deletions src/dstack/_internal/cli/utils/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pathlib import Path
from typing import Any, Optional

import requests
import httpx2
from rich.console import Console
from rich.file_proxy import FileProxy
from rich.prompt import Confirm
Expand All @@ -18,6 +18,7 @@
from dstack._internal.core.models.backends.base import BackendType
from dstack._internal.core.models.instances import InstanceAvailability
from dstack._internal.utils.common import get_dstack_dir, parse_since
from dstack._internal.utils.http import HTTPClient

_colors = {
"secondary": "grey58",
Expand Down Expand Up @@ -173,14 +174,11 @@ def resolve_url(url: str, timeout: float = 5.0) -> str:
if not url.startswith("http://") and not url.startswith("https://"):
url = "http://" + url
try:
response = requests.get(
url,
allow_redirects=True,
timeout=timeout,
)
except requests.exceptions.ConnectionError as e:
with HTTPClient(timeout=timeout, follow_redirects=True) as client:
response = client.get(url)
except (httpx2.HTTPError, httpx2.InvalidURL) as e:
raise ValueError(f"Failed to resolve url {url}") from e
return response.url
return str(response.url)


def format_entity_reference(name: str, project: str, current_project: str) -> str:
Expand Down
18 changes: 9 additions & 9 deletions src/dstack/_internal/cli/utils/updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
from pathlib import Path
from typing import Optional

import requests
from packaging import version as pkg_version

from dstack import version
from dstack._internal.cli.utils.common import error_console
from dstack._internal.utils.http import HTTPClient
from dstack._internal.utils.logging import get_logger

logger = get_logger(__name__)
Expand All @@ -29,14 +29,14 @@ def anonymous_installation_id() -> str:
def get_latest_version() -> Optional[str]:
latest_version_url = f"https://get.dstack.ai/{_get_channel()}/latest-version"
try:
response = requests.get(
latest_version_url,
params={
"anonymous_installation_id": anonymous_installation_id(),
"version": version.__version__,
},
timeout=5,
)
with HTTPClient(timeout=5, follow_redirects=True) as client:
response = client.get(
latest_version_url,
params={
"anonymous_installation_id": anonymous_installation_id(),
"version": version.__version__,
},
)
if response.status_code == 200:
return response.text.strip()
else:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from contextlib import closing
from typing import Optional

from dstack._internal.core.backends.amddevcloud.backend import AMDDevCloudBackend
Expand All @@ -23,7 +24,7 @@ def get_backend(self, record: BackendRecord) -> BaseDigitalOceanBackend:
return AMDDevCloudBackend(config=config, api_url=self.API_URL)

def _validate_creds(self, creds: AnyBaseDigitalOceanCreds, project_name: Optional[str] = None):
api_client = DigitalOceanAPIClient(creds.api_key, self.API_URL)
api_client.validate_api_key()
if project_name:
api_client.validate_project_name(project_name)
with closing(DigitalOceanAPIClient(creds.api_key, self.API_URL)) as api_client:
api_client.validate_api_key()
if project_name:
api_client.validate_project_name(project_name)
27 changes: 14 additions & 13 deletions src/dstack/_internal/core/backends/base/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from typing import Callable, ClassVar, Dict, List, Optional, Union

import git
import requests
import yaml
from cachetools import Cache, TTLCache, cachedmethod
from gpuhunt import CPUArchitecture
Expand Down Expand Up @@ -54,6 +53,7 @@
VolumeProvisioningData,
)
from dstack._internal.core.services import is_valid_dstack_resource_name
from dstack._internal.utils.http import HTTPClient
from dstack._internal.utils.logging import get_logger
from dstack._internal.utils.path import PathLike

Expand Down Expand Up @@ -1381,17 +1381,17 @@ def get_latest_runner_build() -> Optional[str]:
else:
return None

resp = requests.get(
f"https://api.github.com/repos/{owner_repo}/actions/workflows/{workflow_id}/runs",
headers={
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
params={
"status": "success",
},
timeout=10,
)
with HTTPClient(timeout=10, follow_redirects=True) as client:
resp = client.get(
f"https://api.github.com/repos/{owner_repo}/actions/workflows/{workflow_id}/runs",
headers={
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
params={
"status": "success",
},
)
resp.raise_for_status()

head = repo.head.commit
Expand Down Expand Up @@ -1469,7 +1469,8 @@ def requires_nvidia_proprietary_kernel_modules(gpu_name: str) -> bool:


def _fetch_version(url: str) -> Optional[str]:
r = requests.get(url, timeout=5)
with HTTPClient(timeout=5, follow_redirects=True) as client:
r = client.get(url)
r.raise_for_status()
version = r.text.strip()
if not version:
Expand Down
25 changes: 14 additions & 11 deletions src/dstack/_internal/core/backends/cloudrift/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import re
from typing import Any, Dict, List, Mapping, Optional, Union

import requests
import httpx2
from packaging import version
from requests import Response

from dstack._internal.core.errors import BackendError, BackendInvalidCredentialsError
from dstack._internal.utils.http import HTTPClient
from dstack._internal.utils.logging import get_logger

logger = get_logger(__name__)
Expand All @@ -20,6 +20,10 @@ class RiftClient:
def __init__(self, api_key: Optional[str] = None):
self.public_api_root = os.path.join(CLOUDRIFT_SERVER_ADDRESS, "api/v1")
self.api_key = api_key
self._client = HTTPClient(follow_redirects=True, timeout=15)

def close(self) -> None:
self._client.close()

def validate_api_key(self) -> bool:
"""
Expand Down Expand Up @@ -185,7 +189,7 @@ def _make_request(
data: Optional[Mapping[str, Any]] = None,
method: str = "POST",
**kwargs,
) -> Union[Mapping[str, Any], str, Response]:
) -> Union[Mapping[str, Any], str, httpx2.Response]:
headers = {}
if self.api_key is not None:
headers["X-API-Key"] = self.api_key
Expand All @@ -194,16 +198,15 @@ def _make_request(
full_url = f"{self.public_api_root}/{endpoint}"

try:
response = requests.request(
response = self._client.request(
method,
full_url,
headers=headers,
json={"version": version, "data": data},
timeout=15,
**kwargs,
)

if not response.ok:
if response.is_error:
response.raise_for_status()
try:
response_json = response.json()
Expand All @@ -216,12 +219,12 @@ def _make_request(
response_json["version"],
)
return response_json["data"]
except requests.exceptions.JSONDecodeError:
except ValueError: # JSONDecodeError or UnicodeDecodeError
return response
except requests.HTTPError as e:
if e.response is not None and e.response.status_code in (
requests.codes.forbidden,
requests.codes.unauthorized,
except httpx2.HTTPStatusError as e:
if e.response.status_code in (
httpx2.codes.FORBIDDEN,
httpx2.codes.UNAUTHORIZED,
):
raise BackendInvalidCredentialsError(e.response.text)
raise
3 changes: 3 additions & 0 deletions src/dstack/_internal/core/backends/cloudrift/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ def __init__(self, config: CloudRiftConfig):
self.config = config
self.client = RiftClient(self.config.creds.api_key)

def close(self) -> None:
self.client.close()

def get_all_offers_with_availability(
self, unallocated_resources: bool
) -> List[InstanceOfferWithAvailability]:
Expand Down
6 changes: 4 additions & 2 deletions src/dstack/_internal/core/backends/cloudrift/configurator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
from contextlib import closing

from dstack._internal.core.backends.base.configurator import (
BackendRecord,
Expand Down Expand Up @@ -71,6 +72,7 @@ def _get_config(self, record: BackendRecord) -> CloudRiftConfig:
def _validate_creds(self, creds: AnyCloudRiftCreds):
if not isinstance(creds, CloudRiftCreds):
raise_invalid_credentials_error(fields=[["creds"]])
client = RiftClient(creds.api_key)
if not client.validate_api_key():
with closing(RiftClient(creds.api_key)) as client:
is_valid = client.validate_api_key()
if not is_valid:
raise_invalid_credentials_error(fields=[["creds", "api_key"]])
3 changes: 3 additions & 0 deletions src/dstack/_internal/core/backends/crusoe/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ def __init__(self, config: CrusoeConfig):
)
)

def close(self) -> None:
self._client.close()

def get_all_offers_with_availability(
self, unallocated_resources: bool
) -> List[InstanceOfferWithAvailability]:
Expand Down
46 changes: 25 additions & 21 deletions src/dstack/_internal/core/backends/crusoe/configurator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
from contextlib import closing

from dstack._internal.core.backends.base.configurator import (
BackendRecord,
Expand Down Expand Up @@ -28,27 +29,8 @@ class CrusoeConfigurator(
BACKEND_CLASS = CrusoeBackend

def validate_config(self, config: CrusoeBackendConfigWithCreds, default_creds_enabled: bool):
try:
client = CrusoeClient(config.creds, config.project_id)
client.list_quotas()
except Exception as e:
raise_invalid_credentials_error(
fields=[["creds"]],
details=str(e),
)
if config.regions:
try:
available = set(client.list_locations())
except Exception:
return
invalid = set(config.regions) - available
if invalid:
raise_invalid_credentials_error(
fields=[["regions"]],
details=(
f"Unknown regions: {sorted(invalid)}. Valid regions: {sorted(available)}"
),
)
with closing(CrusoeClient(config.creds, config.project_id)) as client:
self._validate_config(client, config)

def create_backend(
self, project_name: str, config: CrusoeBackendConfigWithCreds
Expand Down Expand Up @@ -80,3 +62,25 @@ def _get_config(self, record: BackendRecord) -> CrusoeConfig:
"creds": validate_json_extra_ignore(CrusoeCreds, record.auth),
},
)

def _validate_config(self, client: CrusoeClient, config: CrusoeBackendConfigWithCreds):
try:
client.list_quotas()
except Exception as e:
raise_invalid_credentials_error(
fields=[["creds"]],
details=str(e),
)
if config.regions:
try:
available = set(client.list_locations())
except Exception:
return
invalid = set(config.regions) - available
if invalid:
raise_invalid_credentials_error(
fields=[["regions"]],
details=(
f"Unknown regions: {sorted(invalid)}. Valid regions: {sorted(available)}"
),
)
Loading
Loading