| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import sys |
| 5 |
import threading |
| 6 |
from errno import EIO |
| 7 |
from queue import Queue |
| 8 |
from typing import TYPE_CHECKING, TypeVar |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
from filelock import AsyncAcquireReturnProxy, AsyncFileLock, ContextErrorPolicy |
| 13 |
from tests.async_filelock_cancellation_helpers import assert_file_lock_state, get_fcntl |
| 14 |
from tests.capability_marks import NEEDS_FCNTL, XFAIL_WITHOUT_COROUTINE_CANCELLATION |
| 15 |
|
| 16 |
if sys.version_info >= (3, 11): # pragma: no cover (py311+) |
| 17 |
from builtins import BaseExceptionGroup # pragma: >=3.11 cover |
| 18 |
else: # pragma: no cover (<py311) |
| 19 |
from exceptiongroup import BaseExceptionGroup |
| 20 |
|
| 21 |
if TYPE_CHECKING: |
| 22 |
from collections.abc import Coroutine |
| 23 |
from pathlib import Path |
| 24 |
|
| 25 |
from pytest_mock import MockerFixture |
| 26 |
|
| 27 |
_T = TypeVar("_T") |
| 28 |
|
| 29 |
|
| 30 |
class _CancellationObservedTask(asyncio.Task[_T]): # pragma: needs fcntl |
| 31 |
def __init__( |
| 32 |
self, |
| 33 |
coroutine: Coroutine[None, None, _T], |
| 34 |
cancellation_seen: threading.Event, |
| 35 |
*, |
| 36 |
loop: asyncio.AbstractEventLoop, |
| 37 |
) -> None: |
| 38 |
self._cancellation_seen = cancellation_seen |
| 39 |
super().__init__(coroutine, loop=loop) |
| 40 |
|
| 41 |
def cancel(self, msg: object | None = None) -> bool: |
| 42 |
# Task.cancel accepts arbitrary payloads; object is the narrowest accurate type for its public contract. |
| 43 |
self._cancellation_seen.set() |
| 44 |
return super().cancel(msg) |
| 45 |
|
| 46 |
|
| 47 |
@NEEDS_FCNTL |
| 48 |
def test_runner_shutdown_waits_for_executor_acquire_rollback(tmp_path: Path) -> None: # pragma: needs fcntl |
| 49 |
hook_started = threading.Event() |
| 50 |
finish_hook = threading.Event() |
| 51 |
cancellation_seen = threading.Event() |
| 52 |
|
| 53 |
def block_hook(_fd: int) -> None: |
| 54 |
hook_started.set() |
| 55 |
assert finish_hook.wait(timeout=5) |
| 56 |
|
| 57 |
lock = AsyncFileLock(tmp_path / "a", on_acquired=block_hook) |
| 58 |
tasks: Queue[asyncio.Task[AsyncAcquireReturnProxy]] = Queue() |
| 59 |
runner = threading.Thread( |
| 60 |
target=_run_unawaited_acquire, |
| 61 |
args=(lock, hook_started, cancellation_seen, tasks), |
| 62 |
) |
| 63 |
runner.start() |
| 64 |
try: |
| 65 |
tasks.get(timeout=5) |
| 66 |
assert hook_started.wait(timeout=5) |
| 67 |
assert cancellation_seen.wait(timeout=5), "asyncio runner did not cancel the pending lock task" |
| 68 |
finally: |
| 69 |
finish_hook.set() |
| 70 |
runner.join(timeout=5) |
| 71 |
|
| 72 |
assert (runner.is_alive(), lock.is_locked, lock.lock_counter) == (False, False, 0) |
| 73 |
assert_file_lock_state(str(tmp_path / "a"), available=True) |
| 74 |
|
| 75 |
|
| 76 |
@NEEDS_FCNTL |
| 77 |
@pytest.mark.parametrize("policy", [pytest.param("chain", id="chain"), pytest.param("group", id="group")]) |
| 78 |
@XFAIL_WITHOUT_COROUTINE_CANCELLATION |
| 79 |
def test_runner_shutdown_preserves_body_cancellation_and_release_errors( # pragma: needs fcntl |
| 80 |
tmp_path: Path, mocker: MockerFixture, policy: ContextErrorPolicy |
| 81 |
) -> None: |
| 82 |
body_error = ValueError("body failed") |
| 83 |
prior_error = LookupError("prior release failure") |
| 84 |
release_error = OSError(EIO, "release failed") |
| 85 |
release_error.__context__ = prior_error |
| 86 |
release_started = threading.Event() |
| 87 |
finish_release = threading.Event() |
| 88 |
failed = False |
| 89 |
fcntl = get_fcntl() |
| 90 |
real_flock = fcntl.flock |
| 91 |
|
| 92 |
def fail_first_unlock(fd: int, operation: int) -> None: |
| 93 |
nonlocal failed |
| 94 |
if operation & fcntl.LOCK_UN and not failed: |
| 95 |
failed = True |
| 96 |
release_started.set() |
| 97 |
assert finish_release.wait(timeout=5) |
| 98 |
raise release_error |
| 99 |
real_flock(fd, operation) |
| 100 |
|
| 101 |
mocker.patch("filelock._unix.fcntl.flock", side_effect=fail_first_unlock) |
| 102 |
lock = AsyncFileLock(tmp_path / "a", thread_local=False, context_error_policy=policy) |
| 103 |
runner, task, cancellation_seen = _start_unawaited_context_failure( |
| 104 |
lock, |
| 105 |
body_error, |
| 106 |
release_started, |
| 107 |
) |
| 108 |
try: |
| 109 |
assert release_started.wait(timeout=5) |
| 110 |
assert cancellation_seen.wait(timeout=5), "asyncio runner did not cancel the pending lock task" |
| 111 |
finally: |
| 112 |
finish_release.set() |
| 113 |
runner.join(timeout=5) |
| 114 |
|
| 115 |
assert (runner.is_alive(), task.done()) == (False, True) |
| 116 |
error = task.exception() |
| 117 |
if policy == "chain": |
| 118 |
assert error is release_error |
| 119 |
cancellation = release_error.__context__ |
| 120 |
assert isinstance(cancellation, asyncio.CancelledError) |
| 121 |
assert (cancellation.__context__, prior_error.__context__) == (prior_error, body_error) |
| 122 |
else: |
| 123 |
assert isinstance(error, BaseExceptionGroup) |
| 124 |
cancellation = error.exceptions[1] |
| 125 |
assert isinstance(cancellation, asyncio.CancelledError) |
| 126 |
assert error.exceptions == (body_error, cancellation, release_error) |
| 127 |
assert (cancellation.__context__, release_error.__context__, prior_error.__context__) == ( |
| 128 |
None, |
| 129 |
prior_error, |
| 130 |
None, |
| 131 |
) |
| 132 |
assert (lock.is_locked, lock.lock_counter) == (True, 1) |
| 133 |
assert_file_lock_state(str(tmp_path / "a"), available=False) |
| 134 |
asyncio.run(lock.release()) |
| 135 |
assert_file_lock_state(str(tmp_path / "a"), available=True) |
| 136 |
|
| 137 |
|
| 138 |
def _run_unawaited_acquire( # pragma: needs fcntl |
| 139 |
lock: AsyncFileLock, |
| 140 |
hook_started: threading.Event, |
| 141 |
cancellation_seen: threading.Event, |
| 142 |
tasks: Queue[asyncio.Task[AsyncAcquireReturnProxy]], |
| 143 |
) -> None: |
| 144 |
async def start_acquire() -> None: |
| 145 |
tasks.put( |
| 146 |
_CancellationObservedTask( |
| 147 |
lock.acquire(), |
| 148 |
cancellation_seen, |
| 149 |
loop=asyncio.get_running_loop(), |
| 150 |
) |
| 151 |
) |
| 152 |
assert await asyncio.to_thread(hook_started.wait, 5) |
| 153 |
|
| 154 |
asyncio.run(start_acquire()) |
| 155 |
|
| 156 |
|
| 157 |
def _start_unawaited_context_failure( # pragma: needs fcntl |
| 158 |
lock: AsyncFileLock, |
| 159 |
body_error: BaseException, |
| 160 |
release_started: threading.Event, |
| 161 |
) -> tuple[threading.Thread, asyncio.Task[None], threading.Event]: |
| 162 |
tasks: Queue[asyncio.Task[None]] = Queue() |
| 163 |
cancellation_seen = threading.Event() |
| 164 |
runner = threading.Thread( |
| 165 |
target=_run_unawaited_context_failure, |
| 166 |
args=(lock, body_error, release_started, cancellation_seen, tasks), |
| 167 |
) |
| 168 |
runner.start() |
| 169 |
task = tasks.get(timeout=5) |
| 170 |
return runner, task, cancellation_seen |
| 171 |
|
| 172 |
|
| 173 |
def _run_unawaited_context_failure( # pragma: needs fcntl |
| 174 |
lock: AsyncFileLock, |
| 175 |
body_error: BaseException, |
| 176 |
release_started: threading.Event, |
| 177 |
cancellation_seen: threading.Event, |
| 178 |
tasks: Queue[asyncio.Task[None]], |
| 179 |
) -> None: |
| 180 |
async def fail_in_context() -> None: |
| 181 |
async with lock: |
| 182 |
raise body_error |
| 183 |
|
| 184 |
async def start_context() -> None: |
| 185 |
tasks.put( |
| 186 |
_CancellationObservedTask( |
| 187 |
fail_in_context(), |
| 188 |
cancellation_seen, |
| 189 |
loop=asyncio.get_running_loop(), |
| 190 |
) |
| 191 |
) |
| 192 |
assert await asyncio.to_thread(release_started.wait, 5) |
| 193 |
|
| 194 |
asyncio.run(start_context()) |