Skip to content
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

Cache construction of middleware handlers #9158

Merged
merged 7 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
29 changes: 24 additions & 5 deletions aiohttp/web_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
Expand All @@ -30,7 +31,7 @@
from . import hdrs
from .helpers import AppKey
from .log import web_logger
from .typedefs import Middleware
from .typedefs import Handler, Middleware
from .web_exceptions import NotAppKeyWarning
from .web_middlewares import _fix_request_current_app
from .web_request import Request
Expand Down Expand Up @@ -79,6 +80,7 @@ class Application(MutableMapping[Union[str, AppKey[Any]], Any]):
"_handler_args",
"_middlewares",
"_middlewares_handlers",
"_middlewares_cache",
"_run_middlewares",
"_state",
"_frozen",
Expand Down Expand Up @@ -117,6 +119,7 @@ def __init__(
self._middlewares_handlers: _MiddlewaresHandlers = tuple()
# initialized on freezing
self._run_middlewares: Optional[bool] = None
self._middlewares_cache: Dict[Tuple[Handler, Tuple[int, ...]], Handler] = {}

self._state: Dict[Union[AppKey[Any], str], object] = {}
self._frozen = False
Expand Down Expand Up @@ -380,15 +383,31 @@ async def _handle(self, request: Request) -> StreamResponse:
handler = match_info.handler

if self._run_middlewares:
for app in match_info.apps[::-1]:
assert app.pre_frozen, "middleware handlers are not ready"
for m in app._middlewares_handlers:
handler = update_wrapper(partial(m, handler=handler), handler)
handler = self._apply_middlewares(handler, match_info.apps[::-1])

resp = await handler(request)

return resp

def _apply_middlewares(
self,
handler: Handler,
apps: Tuple["Application", ...],
) -> Callable[[Request], Awaitable[StreamResponse]]:
"""Apply middlewares to handler."""
cache_key = (handler, tuple(id(app) for app in apps))
Dreamsorcerer marked this conversation as resolved.
Show resolved Hide resolved

if cache_key in self._middlewares_cache:
return self._middlewares_cache[cache_key]

for app in apps:
assert app.pre_frozen, "middleware handlers are not ready"
for m in app._middlewares_handlers:
handler = update_wrapper(partial(m, handler=handler), handler)

self._middlewares_cache[cache_key] = handler
return handler

def __call__(self) -> "Application":
"""gunicorn compatibility"""
return self
Expand Down
22 changes: 14 additions & 8 deletions tests/test_web_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,13 @@ async def middleware(request, handler: Handler):
app.middlewares.append(middleware)
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 201 == resp.status
txt = await resp.text()
assert "OK[MIDDLEWARE]" == txt

# Call twice to verify cache works
for _ in range(2):
resp = await client.get("/")
assert 201 == resp.status
txt = await resp.text()
assert "OK[MIDDLEWARE]" == txt


async def test_middleware_handles_exception(loop: Any, aiohttp_client: Any) -> None:
Expand All @@ -42,10 +45,13 @@ async def middleware(request, handler: Handler):
app.middlewares.append(middleware)
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 501 == resp.status
txt = await resp.text()
assert "Error text[MIDDLEWARE]" == txt

# Call twice to verify cache works
for _ in range(2):
resp = await client.get("/")
assert 501 == resp.status
txt = await resp.text()
assert "Error text[MIDDLEWARE]" == txt


async def test_middleware_chain(loop: Any, aiohttp_client: Any) -> None:
Expand Down
Loading