Skip to content

Commit ab262b4

Browse files
lesnik512claude
andcommitted
feat(client): AsyncClient construction and ownership semantics
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 1566544 commit ab262b4

3 files changed

Lines changed: 241 additions & 3 deletions

File tree

‎src/httpware/__init__.py‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,52 @@
11
"""httpware — thin async HTTP client wrapper over httpx2."""
22

3-
from httpware.decoders import ResponseDecoder as ResponseDecoder
4-
from httpware.decoders.pydantic import PydanticDecoder as PydanticDecoder
3+
from httpware.client import AsyncClient
4+
from httpware.decoders import ResponseDecoder
5+
from httpware.decoders.pydantic import PydanticDecoder
6+
from httpware.errors import (
7+
STATUS_TO_EXCEPTION,
8+
BadRequestError,
9+
ClientError,
10+
ClientStatusError,
11+
ConflictError,
12+
ForbiddenError,
13+
InternalServerError,
14+
NotFoundError,
15+
RateLimitedError,
16+
ServerStatusError,
17+
ServiceUnavailableError,
18+
StatusError,
19+
TimeoutError, # noqa: A004
20+
TransportError,
21+
UnauthorizedError,
22+
UnprocessableEntityError,
23+
)
24+
from httpware.middleware import Middleware, Next, after_response, before_request, on_error
25+
26+
27+
__all__ = [
28+
"STATUS_TO_EXCEPTION",
29+
"AsyncClient",
30+
"BadRequestError",
31+
"ClientError",
32+
"ClientStatusError",
33+
"ConflictError",
34+
"ForbiddenError",
35+
"InternalServerError",
36+
"Middleware",
37+
"Next",
38+
"NotFoundError",
39+
"PydanticDecoder",
40+
"RateLimitedError",
41+
"ResponseDecoder",
42+
"ServerStatusError",
43+
"ServiceUnavailableError",
44+
"StatusError",
45+
"TimeoutError",
46+
"TransportError",
47+
"UnauthorizedError",
48+
"UnprocessableEntityError",
49+
"after_response",
50+
"before_request",
51+
"on_error",
52+
]

‎src/httpware/client.py‎

Lines changed: 116 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,116 @@
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

‎tests/test_client_construction.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""Tests for AsyncClient construction and ownership semantics."""
2+
3+
import httpx2
4+
import pytest
5+
6+
from httpware import AsyncClient
7+
from httpware.decoders.pydantic import PydanticDecoder
8+
9+
10+
def test_construction_with_no_args_works() -> None:
11+
client = AsyncClient()
12+
assert isinstance(client, AsyncClient)
13+
14+
15+
def test_construction_with_forwarded_kwargs() -> None:
16+
client = AsyncClient(
17+
base_url="https://example.test",
18+
headers={"x-shared": "1"},
19+
params={"trace": "yes"},
20+
timeout=10.0,
21+
)
22+
assert isinstance(client, AsyncClient)
23+
24+
25+
def test_construction_with_caller_owned_httpx2_client() -> None:
26+
transport = httpx2.MockTransport(lambda req: httpx2.Response(200, request=req))
27+
caller = httpx2.AsyncClient(transport=transport)
28+
client = AsyncClient(httpx2_client=caller)
29+
assert isinstance(client, AsyncClient)
30+
31+
32+
@pytest.mark.parametrize(
33+
"kwargs",
34+
[
35+
{"base_url": "https://example.test"},
36+
{"headers": {"x": "1"}},
37+
{"params": {"x": "1"}},
38+
{"cookies": {"x": "1"}},
39+
{"timeout": 5.0},
40+
{"limits": httpx2.Limits(max_connections=10)},
41+
{"auth": httpx2.BasicAuth("u", "p")},
42+
],
43+
)
44+
def test_caller_owned_client_with_forwarded_kwargs_is_typeerror(kwargs: dict) -> None:
45+
transport = httpx2.MockTransport(lambda req: httpx2.Response(200, request=req))
46+
caller = httpx2.AsyncClient(transport=transport)
47+
with pytest.raises(TypeError, match="httpx2_client"):
48+
AsyncClient(httpx2_client=caller, **kwargs)
49+
50+
51+
def test_default_decoder_is_pydantic_decoder() -> None:
52+
client = AsyncClient()
53+
assert isinstance(client._decoder, PydanticDecoder) # noqa: SLF001
54+
55+
56+
def test_explicit_decoder_is_honored() -> None:
57+
class _Stub:
58+
def decode(self, content: bytes, model: type) -> object: # noqa: ARG002
59+
return None
60+
61+
client = AsyncClient(decoder=_Stub())
62+
assert isinstance(client._decoder, _Stub) # noqa: SLF001
63+
64+
65+
def test_explicit_middleware_is_honored() -> None:
66+
captured: list[str] = []
67+
68+
class _Tag:
69+
async def __call__(self, request, next) -> httpx2.Response: # noqa: A002, ANN001
70+
captured.append("tag")
71+
return await next(request)
72+
73+
client = AsyncClient(middleware=(_Tag(),))
74+
assert client._user_middleware == (client._user_middleware[0],) # noqa: SLF001
75+
assert len(client._user_middleware) == 1 # noqa: SLF001

0 commit comments

Comments
 (0)