Skip to content

Commit

Permalink
[PR #9168/5e15ea61 backport][3.11] Avoid creating handler waiter unti…
Browse files Browse the repository at this point in the history
…l shutdown (#9211)
  • Loading branch information
patchback[bot] authored Sep 21, 2024
1 parent 6608ffe commit 0408ba6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGES/9168.misc.rst
14 changes: 11 additions & 3 deletions aiohttp/web_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ class RequestHandler(BaseProtocol):
"_force_close",
"_current_request",
"_timeout_ceil_threshold",
"_request_in_progress",
)

def __init__(
Expand Down Expand Up @@ -238,6 +239,7 @@ def __init__(

self._close = False
self._force_close = False
self._request_in_progress = False

def __repr__(self) -> str:
return "<{} {}>".format(
Expand All @@ -261,7 +263,11 @@ async def shutdown(self, timeout: Optional[float] = 15.0) -> None:
self._keepalive_handle.cancel()

# Wait for graceful handler completion
if self._handler_waiter is not None:
if self._request_in_progress:
# The future is only created when we are shutting
# down while the handler is still processing a request
# to avoid creating a future for every request.
self._handler_waiter = self._loop.create_future()
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
async with ceil_timeout(timeout):
await self._handler_waiter
Expand Down Expand Up @@ -446,7 +452,7 @@ async def _handle_request(
start_time: float,
request_handler: Callable[[BaseRequest], Awaitable[StreamResponse]],
) -> Tuple[StreamResponse, bool]:
self._handler_waiter = self._loop.create_future()
self._request_in_progress = True
try:
try:
self._current_request = request
Expand Down Expand Up @@ -477,7 +483,9 @@ async def _handle_request(

resp, reset = await self.finish_response(request, resp, start_time)
finally:
self._handler_waiter.set_result(None)
self._request_in_progress = False
if self._handler_waiter is not None:
self._handler_waiter.set_result(None)

return resp, reset

Expand Down

0 comments on commit 0408ba6

Please sign in to comment.