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

Modify _drain_helper() to handle parallel calls without race-condition #6028

Merged
merged 4 commits into from
Oct 27, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions CHANGES/2934.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Modify _drain_helper() to handle concurrent `await resp.write(...)` or `ws.send_json(...)` calls without race-condition.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ Navid Sheikhol
Nicolas Braem
Nikolay Kim
Nikolay Novik
Nándor Mátravölgyi
Oisin Aylward
Olaf Conradi
Oleg Höfling
Expand Down
8 changes: 4 additions & 4 deletions aiohttp/base_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ async def _drain_helper(self) -> None:
if not self._paused:
return
waiter = self._drain_waiter
assert waiter is None or waiter.cancelled()
waiter = self._loop.create_future()
self._drain_waiter = waiter
await waiter
if waiter is None:
waiter = self._loop.create_future()
self._drain_waiter = waiter
await asyncio.shield(waiter)
asvetlov marked this conversation as resolved.
Show resolved Hide resolved
18 changes: 18 additions & 0 deletions tests/test_base_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,21 @@ async def wait() -> None:
with suppress(asyncio.CancelledError):
await t
assert pr._drain_waiter is None


async def test_parallel_drain_race_condition() -> None:
loop = asyncio.get_event_loop()
pr = BaseProtocol(loop=loop)
tr = mock.Mock()
pr.connection_made(tr)
pr.pause_writing()

ts = [loop.create_task(pr._drain_helper()) for _ in range(5)]
assert not (await asyncio.wait(ts, timeout=0.5))[
0
], "All draining tasks must be pending"

assert pr._drain_waiter is not None
pr.resume_writing()
await asyncio.gather(*ts)
assert pr._drain_waiter is None