|
1 | | -"""AsyncClient — implemented in later tasks of the v0.2 pivot.""" |
| 1 | +"""AsyncClient — the thin httpx2 wrapper.""" |
| 2 | + |
| 3 | +import typing |
| 4 | +from collections.abc import Sequence |
| 5 | +from http import HTTPStatus |
| 6 | + |
| 7 | +import httpx2 |
| 8 | + |
| 9 | +from httpware.decoders import ResponseDecoder |
| 10 | +from httpware.decoders.pydantic import PydanticDecoder |
| 11 | +from httpware.errors import ( |
| 12 | + STATUS_TO_EXCEPTION, |
| 13 | + ClientStatusError, |
| 14 | + ServerStatusError, |
| 15 | + TimeoutError, # noqa: A004 |
| 16 | + TransportError, |
| 17 | +) |
| 18 | +from httpware.middleware import Middleware, Next |
| 19 | +from httpware.middleware.chain import compose |
| 20 | + |
| 21 | + |
| 22 | +T = typing.TypeVar("T") |
| 23 | + |
| 24 | + |
| 25 | +_FORWARDED_KWARG_NAMES = ("base_url", "headers", "params", "cookies", "timeout", "limits", "auth") |
| 26 | +_HTTPX2_CLIENT_CONFLICT_MESSAGE = ( |
| 27 | + "AsyncClient(httpx2_client=...) cannot be combined with any of " |
| 28 | + f"{_FORWARDED_KWARG_NAMES}; configure the httpx2.AsyncClient you pass instead." |
| 29 | +) |
| 30 | + |
| 31 | +_CLIENT_ERROR_LOW = HTTPStatus.BAD_REQUEST.value # 400 |
| 32 | +_SERVER_ERROR_LOW = HTTPStatus.INTERNAL_SERVER_ERROR.value # 500 |
| 33 | +_SERVER_ERROR_HIGH = 600 # synthetic upper bound; no standard HTTP status reaches this |
| 34 | + |
| 35 | + |
| 36 | +class AsyncClient: |
| 37 | + """Async HTTP client: thin wrapper around httpx2 with typed decoding and middleware.""" |
| 38 | + |
| 39 | + _httpx2_client: httpx2.AsyncClient |
| 40 | + _owns_client: bool |
| 41 | + _decoder: ResponseDecoder |
| 42 | + _user_middleware: tuple[Middleware, ...] |
| 43 | + _dispatch: Next |
| 44 | + |
| 45 | + def __init__( # noqa: PLR0913 — wide constructor is the cost of a single-call API |
| 46 | + self, |
| 47 | + *, |
| 48 | + base_url: str = "", |
| 49 | + headers: dict[str, str] | None = None, |
| 50 | + params: dict[str, str] | None = None, |
| 51 | + cookies: dict[str, str] | None = None, |
| 52 | + timeout: httpx2.Timeout | float | None = None, |
| 53 | + limits: httpx2.Limits | None = None, |
| 54 | + auth: httpx2.Auth | None = None, |
| 55 | + httpx2_client: httpx2.AsyncClient | None = None, |
| 56 | + decoder: ResponseDecoder | None = None, |
| 57 | + middleware: Sequence[Middleware] = (), |
| 58 | + ) -> None: |
| 59 | + if httpx2_client is not None: |
| 60 | + forwarded = { |
| 61 | + "base_url": base_url, |
| 62 | + "headers": headers, |
| 63 | + "params": params, |
| 64 | + "cookies": cookies, |
| 65 | + "timeout": timeout, |
| 66 | + "limits": limits, |
| 67 | + "auth": auth, |
| 68 | + } |
| 69 | + if any(value not in (None, "") for value in forwarded.values()): |
| 70 | + raise TypeError(_HTTPX2_CLIENT_CONFLICT_MESSAGE) |
| 71 | + self._httpx2_client = httpx2_client |
| 72 | + self._owns_client = False |
| 73 | + else: |
| 74 | + kwargs: dict[str, typing.Any] = {} |
| 75 | + if base_url: |
| 76 | + kwargs["base_url"] = base_url |
| 77 | + if headers is not None: |
| 78 | + kwargs["headers"] = headers |
| 79 | + if params is not None: |
| 80 | + kwargs["params"] = params |
| 81 | + if cookies is not None: |
| 82 | + kwargs["cookies"] = cookies |
| 83 | + if timeout is not None: |
| 84 | + kwargs["timeout"] = timeout |
| 85 | + if limits is not None: |
| 86 | + kwargs["limits"] = limits |
| 87 | + if auth is not None: |
| 88 | + kwargs["auth"] = auth |
| 89 | + self._httpx2_client = httpx2.AsyncClient(**kwargs) |
| 90 | + self._owns_client = True |
| 91 | + |
| 92 | + self._decoder = decoder if decoder is not None else PydanticDecoder() |
| 93 | + self._user_middleware = tuple(middleware) |
| 94 | + self._dispatch = compose(self._user_middleware, self._terminal) |
| 95 | + |
| 96 | + async def _terminal(self, request: httpx2.Request) -> httpx2.Response: |
| 97 | + try: |
| 98 | + response = await self._httpx2_client.send(request) |
| 99 | + except httpx2.TimeoutException as exc: |
| 100 | + raise TimeoutError(str(exc)) from exc |
| 101 | + except (httpx2.InvalidURL, httpx2.CookieConflict) as exc: |
| 102 | + raise TransportError(str(exc)) from exc |
| 103 | + except httpx2.HTTPError as exc: |
| 104 | + raise TransportError(str(exc)) from exc |
| 105 | + except RuntimeError as exc: |
| 106 | + if "closed" in str(exc): |
| 107 | + raise TransportError(str(exc)) from exc |
| 108 | + raise |
| 109 | + status = response.status_code |
| 110 | + if _CLIENT_ERROR_LOW <= status < _SERVER_ERROR_HIGH: |
| 111 | + exc_class = STATUS_TO_EXCEPTION.get( |
| 112 | + status, |
| 113 | + ClientStatusError if status < _SERVER_ERROR_LOW else ServerStatusError, |
| 114 | + ) |
| 115 | + raise exc_class(response) |
| 116 | + return response |
0 commit comments