| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import importlib |
| 4 |
import multiprocessing |
| 5 |
import sys |
| 6 |
import threading |
| 7 |
from typing import TYPE_CHECKING, cast |
| 8 |
|
| 9 |
from filelock import FileLock, Timeout |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
import asyncio |
| 13 |
from multiprocessing.sharedctypes import Synchronized |
| 14 |
from typing import Protocol |
| 15 |
|
| 16 |
class FcntlModule(Protocol): |
| 17 |
LOCK_UN: int |
| 18 |
|
| 19 |
@staticmethod |
| 20 |
def flock(fd: int, operation: int) -> None: ... |
| 21 |
|
| 22 |
|
| 23 |
def assert_cancellation_message(error: asyncio.CancelledError, message: str) -> None: |
| 24 |
# Task.cancel() did not propagate its message to code awaiting the task until Python 3.11. |
| 25 |
assert error.args == ((message,) if sys.version_info >= (3, 11) else ()) |
| 26 |
|
| 27 |
|
| 28 |
def get_fcntl() -> FcntlModule: # pragma: win32 no cover |
| 29 |
return cast("FcntlModule", importlib.import_module("fcntl")) |
| 30 |
|
| 31 |
|
| 32 |
def assert_file_lock_state(lock_file: str, *, available: bool) -> None: |
| 33 |
context = multiprocessing.get_context("spawn") |
| 34 |
acquired = context.Value("b", False) |
| 35 |
probe = context.Process(target=_probe_file_lock, args=(lock_file, acquired)) |
| 36 |
probe.start() |
| 37 |
try: |
| 38 |
probe.join(timeout=5) |
| 39 |
assert not probe.is_alive(), "lock probe did not exit" |
| 40 |
assert (probe.exitcode, acquired.value) == (0, available) |
| 41 |
finally: |
| 42 |
if probe.is_alive(): # pragma: no cover - cleanup for a hung child after the assertion fails |
| 43 |
probe.terminate() |
| 44 |
probe.join(timeout=5) |
| 45 |
probe.close() |
| 46 |
|
| 47 |
|
| 48 |
def start_file_lock_holder(lock_file: str) -> tuple[threading.Thread, threading.Event, threading.Event]: |
| 49 |
holder_started = threading.Event() |
| 50 |
finish_holder = threading.Event() |
| 51 |
holder = threading.Thread(target=_hold_file_lock, args=(lock_file, holder_started, finish_holder)) |
| 52 |
holder.start() |
| 53 |
return holder, holder_started, finish_holder |
| 54 |
|
| 55 |
|
| 56 |
def _probe_file_lock(lock_file: str, acquired: Synchronized[bool]) -> None: |
| 57 |
try: |
| 58 |
with FileLock(lock_file, timeout=0): |
| 59 |
acquired.value = True |
| 60 |
except Timeout: # pragma: win32 no cover |
| 61 |
pass # pragma: win32 no cover |
| 62 |
|
| 63 |
|
| 64 |
def _hold_file_lock(lock_file: str, holder_started: threading.Event, finish_holder: threading.Event) -> None: |
| 65 |
with FileLock(lock_file): |
| 66 |
holder_started.set() |
| 67 |
assert finish_holder.wait(timeout=5) |
| 68 |
|
| 69 |
|
| 70 |
__all__ = ["assert_cancellation_message", "assert_file_lock_state", "get_fcntl", "start_file_lock_holder"] |