Skip to content

Commit

Permalink
ignore_after: patch Task.cancel to separate timeout vs external cancel
Browse files Browse the repository at this point in the history
  • Loading branch information
SomberNight committed Apr 29, 2022
1 parent a0be71c commit 5625003
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
13 changes: 10 additions & 3 deletions aiorpcx/curio.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,9 +324,16 @@ class UncaughtTimeoutError(Exception):

def _set_new_deadline(task, deadline):
def timeout_task():
# Unfortunately task.cancel is all we can do with asyncio
task.cancel()
task._timed_out = deadline
task._orig_cancel()
task._timed_out = None if getattr(task, "_externally_cancelled", False) else deadline
def mycancel(*args, **kwargs):
task._orig_cancel(*args, **kwargs)
task._externally_cancelled = True
task._timed_out = None
# We monkey-patch Task.cancel to distinguish timeouts and external cancellation:
if not hasattr(task, "_orig_cancel"):
task._orig_cancel = task.cancel
task.cancel = mycancel
task._deadline_handle = task._loop.call_at(deadline, timeout_task)


Expand Down
32 changes: 32 additions & 0 deletions tests/test_curio.py
Original file line number Diff line number Diff line change
Expand Up @@ -1112,6 +1112,38 @@ async def test_ignore_at_context():
assert False


# See https://github.com/kyuupichan/aiorpcX/issues/44
@pytest.mark.asyncio
async def test_ignore_after_cancellation_race():
failed_evt = Event()

async def kill_group():
await sleep(0.01)
raise Exception("kill_group")

async def second_timeout():
await sleep(0.2)
failed_evt.set() # mark unit test as failed

async def infinite_loop():
while True:
async with ignore_after(0):
await failed_evt.wait()
break

async with TaskGroup() as group:
await group.spawn(infinite_loop)
await group.spawn(kill_group)
# kill_group is supposed to kill this group soon. The unit test is testing this.
# If that fails, to avoid infinite-looping and to fail the test:
task_second_timeout = await spawn(second_timeout) # top-level spawn
exc = group.exception
assert exc and exc.args and exc.args[0] == "kill_group"
assert not failed_evt.is_set()
# clean-up
task_second_timeout.cancel()


#
# Task group tests snitched from curio
#
Expand Down

0 comments on commit 5625003

Please sign in to comment.