Repository navigation
refactor: route SDK and CLI requests through shared HTTP clients #733
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| """shared HTTP sessions, request lifetimes, and response decoding.""" | ||
|
|
||
| from contextlib import asynccontextmanager, contextmanager | ||
| from typing import Mapping | ||
|
|
||
| import aiohttp | ||
| import requests | ||
| from yarl import URL | ||
|
|
||
| from runpod.user_agent import USER_AGENT | ||
|
|
||
| from .routes import Route, api_base_url | ||
|
|
||
|
|
||
| class HTTPClient: | ||
| """an async transport with an explicitly scoped connection pool.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| base_url: str | None = None, | ||
| *, | ||
| headers: Mapping[str, str] | None = None, | ||
| session: aiohttp.ClientSession | None = None, | ||
| ): | ||
| self.base_url = api_base_url() if base_url is None else base_url | ||
| self.headers = {"User-Agent": USER_AGENT} if session is None else {} | ||
| self.headers.update(headers or {}) | ||
| self.session = session | ||
| self._owns_session = session is None | ||
|
|
||
| async def __aenter__(self): | ||
| if self.session is None: | ||
| self.session = aiohttp.ClientSession(cookie_jar=aiohttp.DummyCookieJar()) | ||
| elif self.session.closed: | ||
| raise RuntimeError("the supplied HTTP session is closed") | ||
| self.session._retry_connection = False | ||
| return self | ||
|
|
||
| async def __aexit__(self, *args): | ||
| await self.close() | ||
|
|
||
| async def close(self): | ||
| if self._owns_session and self.session is not None: | ||
| session, self.session = self.session, None | ||
| await session.close() | ||
|
|
||
| @asynccontextmanager | ||
| async def stream(self, route: Route, *, timeout=30, headers=None, **kwargs): | ||
| if self.session is None: | ||
| async with HTTPClient(self.base_url, headers=self.headers) as client: | ||
| async with client.stream( | ||
| route, timeout=timeout, headers=headers, **kwargs | ||
| ) as response: | ||
| yield response | ||
| return | ||
| self.session._retry_connection = False | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This runs on every |
||
| if not isinstance(timeout, aiohttp.ClientTimeout): | ||
| timeout = aiohttp.ClientTimeout(total=timeout) | ||
| kwargs.setdefault("allow_redirects", False) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| async with self.session.request( | ||
| route.method, | ||
| URL(route.url(self.base_url), encoded=True), | ||
| headers={**self.headers, **(headers or {})}, | ||
| timeout=timeout, | ||
| **kwargs, | ||
| ) as response: | ||
| yield response | ||
|
|
||
| async def request(self, route: Route, *, response_type="json", **kwargs): | ||
| if response_type not in {"json", "text"}: | ||
| raise ValueError("response_type must be json or text") | ||
| async with self.stream(route, **kwargs) as response: | ||
| response.raise_for_status() | ||
| if 300 <= response.status < 400: | ||
| raise aiohttp.ClientResponseError( | ||
| response.request_info, | ||
| response.history, | ||
| status=response.status, | ||
| message="unexpected redirect", | ||
| headers=response.headers, | ||
| ) | ||
| if response_type == "text": | ||
| return await response.text() | ||
| if response.status == 204 or not await response.read(): | ||
| return None | ||
| return await response.json(content_type=None) | ||
|
|
||
|
|
||
| class SyncHTTPClient: | ||
| """a synchronous transport with the same routes and ownership rules.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| base_url: str | None = None, | ||
| *, | ||
| headers: Mapping[str, str] | None = None, | ||
| session: requests.Session | None = None, | ||
| ): | ||
| self.base_url = api_base_url() if base_url is None else base_url | ||
| self.headers = {"User-Agent": USER_AGENT} if session is None else {} | ||
| self.headers.update(headers or {}) | ||
| self.session = session | ||
| self._owns_session = session is None | ||
|
|
||
| def __enter__(self): | ||
| if self.session is None: | ||
| self.session = requests.Session() | ||
| return self | ||
|
|
||
| def __exit__(self, *args): | ||
| self.close() | ||
|
|
||
| def close(self): | ||
| if self._owns_session and self.session is not None: | ||
| session, self.session = self.session, None | ||
| session.close() | ||
|
|
||
| @contextmanager | ||
| def stream(self, route: Route, *, timeout=30, headers=None, **kwargs): | ||
| if self.session is None: | ||
| with SyncHTTPClient(self.base_url, headers=self.headers) as client: | ||
| with client.stream( | ||
| route, timeout=timeout, headers=headers, **kwargs | ||
| ) as response: | ||
| yield response | ||
| return | ||
| kwargs.setdefault("allow_redirects", False) | ||
| response = self.session.request( | ||
| route.method, | ||
| route.url(self.base_url), | ||
| headers={**self.headers, **(headers or {})}, | ||
| timeout=timeout, | ||
| **kwargs, | ||
| ) | ||
| try: | ||
| yield response | ||
| finally: | ||
| response.close() | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
endpoint_base_url()givesRUNPOD_ENDPOINT_BASE_URLpriority over a value assigned in code torunpod.endpoint_url_base. Before this PR,RunPodClientand the asyncio runner readrunpod.endpoint_url_basedirectly. A user who setsrunpod.endpoint_url_base = "https://custom"in a shell that also has the env var set now silently hits the env var's URL. Is that precedence intended? If so, a note in the docs/release notes would help; otherwise an explicit assignment in code should probably win.