Skip to content

Commit

Permalink
Fix handler waiting on shutdown (#8611)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dreamsorcerer authored Aug 7, 2024
1 parent 49bd25a commit 1fcef94
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGES/8611.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed an edge case where shutdown would wait for timeout when handler was already completed -- by :user:`Dreamsorcerer`.
11 changes: 8 additions & 3 deletions aiohttp/web_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ class RequestHandler(BaseProtocol):
"_lingering_time",
"_messages",
"_message_tail",
"_handler_waiter",
"_waiter",
"_task_handler",
"_upgrade",
Expand Down Expand Up @@ -215,6 +216,7 @@ def __init__(
self._message_tail = b""

self._waiter: Optional[asyncio.Future[None]] = None
self._handler_waiter: Optional[asyncio.Future[None]] = None
self._task_handler: Optional[asyncio.Task[None]] = None

self._upgrade = False
Expand Down Expand Up @@ -278,11 +280,11 @@ async def shutdown(self, timeout: Optional[float] = 15.0) -> None:
if self._waiter:
self._waiter.cancel()

# Wait for graceful disconnection
if self._current_request is not None:
# Wait for graceful handler completion
if self._handler_waiter is not None:
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
async with ceil_timeout(timeout):
await self._current_request.wait_for_disconnection()
await self._handler_waiter
# Then cancel handler and wait
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
async with ceil_timeout(timeout):
Expand Down Expand Up @@ -466,6 +468,7 @@ async def _handle_request(
start_time: float,
request_handler: Callable[[BaseRequest], Awaitable[StreamResponse]],
) -> Tuple[StreamResponse, bool]:
self._handler_waiter = self._loop.create_future()
try:
try:
self._current_request = request
Expand All @@ -489,6 +492,8 @@ async def _handle_request(
reset = await self.finish_response(request, resp, start_time)
else:
reset = await self.finish_response(request, resp, start_time)
finally:
self._handler_waiter.set_result(None)

return resp, reset

Expand Down

0 comments on commit 1fcef94

Please sign in to comment.