Skip to content

Commit 635de95

Browse files
lesnik512claude
andcommitted
feat(middleware): protocol and chain retyped on httpx2.Request/Response
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 93142f0 commit 635de95

3 files changed

Lines changed: 256 additions & 1 deletion

File tree

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,77 @@
1-
"""Middleware protocol — implemented in later tasks of the v0.2 pivot."""
1+
"""Middleware protocol, Next type, and phase-shortcut decorators.
2+
3+
Middleware operates directly on httpx2.Request / httpx2.Response — there is
4+
no httpware-owned request type. The chain is composed at AsyncClient.__init__
5+
(see client.py) and frozen for the client's lifetime.
6+
"""
7+
8+
from collections.abc import Awaitable, Callable
9+
from typing import Protocol, TypeAlias, runtime_checkable
10+
11+
import httpx2
12+
13+
14+
Next: TypeAlias = Callable[[httpx2.Request], Awaitable[httpx2.Response]]
15+
16+
17+
@runtime_checkable
18+
class Middleware(Protocol):
19+
"""Structural protocol every middleware satisfies."""
20+
21+
async def __call__(self, request: httpx2.Request, next: Next) -> httpx2.Response: # noqa: A002
22+
"""Process `request`; call `next(request)` to forward, or synthesize a Response."""
23+
...
24+
25+
26+
def before_request(f: Callable[[httpx2.Request], Awaitable[httpx2.Request]]) -> Middleware:
27+
"""Wrap an async request transform into a Middleware."""
28+
29+
class _BeforeRequestMiddleware:
30+
async def __call__(self, request: httpx2.Request, next: Next) -> httpx2.Response: # noqa: A002
31+
return await next(await f(request))
32+
33+
def __repr__(self) -> str:
34+
return f"<before_request({f.__qualname__})>" # ty: ignore[unresolved-attribute]
35+
36+
return _BeforeRequestMiddleware()
37+
38+
39+
def after_response(
40+
f: Callable[[httpx2.Request, httpx2.Response], Awaitable[httpx2.Response]],
41+
) -> Middleware:
42+
"""Wrap an async response transform into a Middleware."""
43+
44+
class _AfterResponseMiddleware:
45+
async def __call__(self, request: httpx2.Request, next: Next) -> httpx2.Response: # noqa: A002
46+
response = await next(request)
47+
return await f(request, response)
48+
49+
def __repr__(self) -> str:
50+
return f"<after_response({f.__qualname__})>" # ty: ignore[unresolved-attribute]
51+
52+
return _AfterResponseMiddleware()
53+
54+
55+
def on_error(
56+
f: Callable[[httpx2.Request, Exception], Awaitable[httpx2.Response | None]],
57+
) -> Middleware:
58+
"""Wrap an async error handler into a Middleware.
59+
60+
Catches Exception (not BaseException), so asyncio.CancelledError propagates.
61+
Handler returning None re-raises; returning a Response replaces the failure.
62+
"""
63+
64+
class _OnErrorMiddleware:
65+
async def __call__(self, request: httpx2.Request, next: Next) -> httpx2.Response: # noqa: A002
66+
try:
67+
return await next(request)
68+
except Exception as exc:
69+
result = await f(request, exc)
70+
if result is None:
71+
raise
72+
return result
73+
74+
def __repr__(self) -> str:
75+
return f"<on_error({f.__qualname__})>" # ty: ignore[unresolved-attribute]
76+
77+
return _OnErrorMiddleware()

‎src/httpware/middleware/chain.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""Chain composition for the middleware stack."""
2+
3+
import typing
4+
from collections.abc import Awaitable, Callable, Sequence
5+
6+
import httpx2
7+
8+
9+
if typing.TYPE_CHECKING:
10+
from httpware.middleware import Middleware
11+
12+
13+
_Next: typing.TypeAlias = Callable[[httpx2.Request], Awaitable[httpx2.Response]]
14+
15+
16+
def compose(middleware: "Sequence[Middleware]", terminal: _Next) -> _Next:
17+
"""Fold `middleware` into a single callable around `terminal`.
18+
19+
The first middleware in the sequence is the outermost wrapper.
20+
"""
21+
dispatch: _Next = terminal
22+
for layer in reversed(middleware):
23+
dispatch = _wrap(layer, dispatch)
24+
return dispatch
25+
26+
27+
def _wrap(layer: "Middleware", inner: _Next) -> _Next:
28+
async def call(request: httpx2.Request) -> httpx2.Response:
29+
return await layer(request, inner)
30+
31+
return call

‎tests/test_middleware.py‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
"""Tests for the Middleware protocol, Next type, chain composition, and decorators."""
2+
3+
import asyncio
4+
5+
import httpx2
6+
import pytest
7+
8+
from httpware.middleware import (
9+
Middleware,
10+
Next,
11+
after_response,
12+
before_request,
13+
on_error,
14+
)
15+
from httpware.middleware.chain import compose
16+
17+
18+
def _make_request(url: str = "https://example.test/x") -> httpx2.Request:
19+
return httpx2.Request("GET", url)
20+
21+
22+
def _make_response(status: int = 200, *, request: httpx2.Request | None = None) -> httpx2.Response:
23+
if request is None:
24+
request = _make_request()
25+
return httpx2.Response(status, request=request)
26+
27+
28+
async def test_middleware_protocol_is_runtime_checkable() -> None:
29+
class _OkMiddleware:
30+
async def __call__(self, request: httpx2.Request, next: Next) -> httpx2.Response: # noqa: A002
31+
return await next(request)
32+
33+
assert isinstance(_OkMiddleware(), Middleware)
34+
35+
36+
async def test_empty_chain_calls_terminal_directly() -> None:
37+
seen: list[httpx2.Request] = []
38+
39+
async def terminal(request: httpx2.Request) -> httpx2.Response:
40+
seen.append(request)
41+
return _make_response(200, request=request)
42+
43+
dispatch = compose((), terminal)
44+
request = _make_request()
45+
response = await dispatch(request)
46+
assert response.status_code == 200 # noqa: PLR2004
47+
assert seen == [request]
48+
49+
50+
async def test_chain_runs_middleware_in_order() -> None:
51+
order: list[str] = []
52+
53+
class _M:
54+
def __init__(self, label: str) -> None:
55+
self.label = label
56+
57+
async def __call__(self, request: httpx2.Request, next: Next) -> httpx2.Response: # noqa: A002
58+
order.append(f"{self.label}.before")
59+
response = await next(request)
60+
order.append(f"{self.label}.after")
61+
return response
62+
63+
async def terminal(request: httpx2.Request) -> httpx2.Response:
64+
order.append("terminal")
65+
return _make_response(200, request=request)
66+
67+
dispatch = compose((_M("a"), _M("b")), terminal)
68+
await dispatch(_make_request())
69+
assert order == ["a.before", "b.before", "terminal", "b.after", "a.after"]
70+
71+
72+
async def test_before_request_decorator_transforms_request() -> None:
73+
@before_request
74+
async def add_header(request: httpx2.Request) -> httpx2.Request:
75+
return httpx2.Request(request.method, request.url, headers={**request.headers, "X-Custom": "1"})
76+
77+
captured: list[httpx2.Request] = []
78+
79+
async def terminal(request: httpx2.Request) -> httpx2.Response:
80+
captured.append(request)
81+
return _make_response(200, request=request)
82+
83+
dispatch = compose((add_header,), terminal)
84+
await dispatch(_make_request())
85+
assert captured[0].headers["x-custom"] == "1"
86+
87+
88+
async def test_after_response_decorator_transforms_response() -> None:
89+
@after_response
90+
async def upgrade_status(request: httpx2.Request, response: httpx2.Response) -> httpx2.Response:
91+
return httpx2.Response(299, request=request, headers=response.headers, content=response.content)
92+
93+
async def terminal(request: httpx2.Request) -> httpx2.Response:
94+
return _make_response(200, request=request)
95+
96+
dispatch = compose((upgrade_status,), terminal)
97+
response = await dispatch(_make_request())
98+
assert response.status_code == 299 # noqa: PLR2004
99+
100+
101+
async def test_on_error_decorator_can_translate_exception() -> None:
102+
@on_error
103+
async def swallow(request: httpx2.Request, exc: Exception) -> httpx2.Response | None:
104+
if isinstance(exc, RuntimeError) and str(exc) == "boom":
105+
return _make_response(503, request=request)
106+
return None
107+
108+
async def terminal(request: httpx2.Request) -> httpx2.Response: # noqa: ARG001
109+
msg = "boom"
110+
raise RuntimeError(msg)
111+
112+
dispatch = compose((swallow,), terminal)
113+
response = await dispatch(_make_request())
114+
assert response.status_code == 503 # noqa: PLR2004
115+
116+
117+
async def test_on_error_returns_none_reraises() -> None:
118+
@on_error
119+
async def passthrough(
120+
request: httpx2.Request, # noqa: ARG001
121+
exc: Exception, # noqa: ARG001
122+
) -> httpx2.Response | None:
123+
return None
124+
125+
async def terminal(request: httpx2.Request) -> httpx2.Response: # noqa: ARG001
126+
msg = "boom"
127+
raise RuntimeError(msg)
128+
129+
dispatch = compose((passthrough,), terminal)
130+
with pytest.raises(RuntimeError, match="boom"):
131+
await dispatch(_make_request())
132+
133+
134+
async def test_on_error_lets_cancelled_propagate() -> None:
135+
@on_error
136+
async def swallow_all(
137+
request: httpx2.Request, # noqa: ARG001
138+
exc: Exception, # noqa: ARG001
139+
) -> httpx2.Response | None:
140+
msg = "should not catch CancelledError"
141+
raise AssertionError(msg)
142+
143+
async def terminal(request: httpx2.Request) -> httpx2.Response: # noqa: ARG001
144+
raise asyncio.CancelledError
145+
146+
dispatch = compose((swallow_all,), terminal)
147+
with pytest.raises(asyncio.CancelledError):
148+
await dispatch(_make_request())

0 commit comments

Comments
 (0)