Debian Codegraph @

src/filelock/_soft_rw/_async.py

raw
1 """Async wrapper around :class:`SoftReadWriteLock` for use with ``asyncio``."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import functools
7 import os
8 from contextlib import asynccontextmanager
9 from typing import TYPE_CHECKING, ParamSpec, TypeVar
10
11 from filelock._async import (
12 _BackendOutcome,
13 _capture_call,
14 _drain_future,
15 _future_result,
16 _raise_cancelled_error,
17 _wait_until_done,
18 )
19
20 from ._sync import SoftReadWriteLock
21
22 if TYPE_CHECKING:
23 from collections.abc import AsyncGenerator, Callable
24 from concurrent import futures
25 from types import TracebackType
26
27 from filelock._api import AcquireReturnProxy
28 from filelock._lease import LeaseCompromise
29
30 _P = ParamSpec("_P")
31 _R = TypeVar("_R")
32
33
34 class AsyncSoftReadWriteLock:
35 """
36 Async wrapper around :class:`SoftReadWriteLock` for ``asyncio`` applications.
37
38 The sync class's blocking filesystem operations run on a thread pool via ``loop.run_in_executor()``. The
39 underlying :class:`SoftReadWriteLock` handles reentrancy, upgrade/downgrade rules, fork handling, the heartbeat
40 and stale eviction, and singleton behavior.
41
42 :param lock_file: path to the lock file; the protocol directory lives next to it as ``<lock_file>.rw``
43 :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
44 :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention
45 :param is_singleton: if ``True``, reuse existing :class:`SoftReadWriteLock` instances per resolved path
46 :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s
47 :param stale_threshold: seconds a holder record may stay unchanged before a contender evicts it; defaults to
48 ``3 * heartbeat_interval``
49 :param poll_interval: seconds between acquire retries under contention; default 0.25 s
50 :param on_compromise: called from the heartbeat thread with a :class:`~filelock.LeaseCompromise` when the hold is
51 lost
52 :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop
53 :param executor: executor for ``run_in_executor``; ``None`` uses the default executor
54
55 .. versionadded:: 3.27.0
56
57 """
58
59 def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option
60 self,
61 lock_file: str | os.PathLike[str],
62 timeout: float = -1,
63 *,
64 blocking: bool = True,
65 is_singleton: bool = True,
66 heartbeat_interval: float = 30.0,
67 stale_threshold: float | None = None,
68 poll_interval: float = 0.25,
69 on_compromise: Callable[[LeaseCompromise], None] | None = None,
70 loop: asyncio.AbstractEventLoop | None = None,
71 executor: futures.Executor | None = None,
72 ) -> None:
73 self._creator_pid = os.getpid()
74 self._lock = SoftReadWriteLock(
75 lock_file,
76 timeout,
77 blocking=blocking,
78 is_singleton=is_singleton,
79 heartbeat_interval=heartbeat_interval,
80 stale_threshold=stale_threshold,
81 poll_interval=poll_interval,
82 on_compromise=on_compromise,
83 )
84 self._loop = loop
85 self._executor = executor
86
87 @property
88 def lock_file(self) -> str:
89 """The path to the lock file passed to the constructor."""
90 return self._lock.lock_file
91
92 @property
93 def timeout(self) -> float:
94 """The default timeout applied when ``acquire_read`` / ``acquire_write`` is called without one."""
95 return self._lock.timeout
96
97 @property
98 def blocking(self) -> bool:
99 """Whether ``acquire_*`` defaults to blocking; ``False`` makes contention raise immediately."""
100 return self._lock.blocking
101
102 @property
103 def generation(self) -> int | None:
104 """The generation the current hold was granted at, a fencing token; ``None`` when no lock is held."""
105 return self._lock.generation
106
107 @property
108 def compromise(self) -> LeaseCompromise | None:
109 """How the current hold was lost, or ``None`` while it stands."""
110 return self._lock.compromise
111
112 @property
113 def loop(self) -> asyncio.AbstractEventLoop | None:
114 """The event loop used for ``run_in_executor``, or ``None`` for the running loop."""
115 return self._loop
116
117 @property
118 def executor(self) -> futures.Executor | None:
119 """The executor used for ``run_in_executor``, or ``None`` for the default executor."""
120 return self._executor
121
122 @asynccontextmanager
123 async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
124 """
125 Async context manager that acquires and releases a shared read lock.
126
127 :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
128 :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
129
130 :raises RuntimeError: if a write lock is already held on this instance
131 :raises Timeout: if the lock cannot be acquired within *timeout* seconds
132
133 """
134 await self.acquire_read(timeout, blocking=blocking)
135 try:
136 yield
137 finally:
138 await self.release()
139
140 @asynccontextmanager
141 async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
142 """
143 Async context manager that acquires and releases an exclusive write lock.
144
145 :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
146 :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
147
148 :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread
149 :raises Timeout: if the lock cannot be acquired within *timeout* seconds
150
151 """
152 await self.acquire_write(timeout, blocking=blocking)
153 try:
154 yield
155 finally:
156 await self.release()
157
158 async def acquire_read(
159 self, timeout: float | None = None, *, blocking: bool | None = None
160 ) -> AsyncAcquireSoftReadWriteReturnProxy:
161 """
162 Acquire a shared read lock.
163
164 See :meth:`SoftReadWriteLock.acquire_read` for reentrancy / upgrade / fork semantics. The blocking work runs
165 inside ``run_in_executor`` so other coroutines on the same loop keep progressing while this call waits.
166
167 :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
168 :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
169
170 :returns: a proxy usable as an async context manager to release the lock
171
172 :raises RuntimeError: if a write lock is already held, if this instance was invalidated by
173 :func:`os.fork`, or if :meth:`close` was called
174 :raises Timeout: if the lock cannot be acquired within *timeout* seconds
175
176 """
177 self._raise_if_inherited()
178 await self._run_acquire(functools.partial(self._lock.acquire_read, timeout, blocking=blocking))
179 return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
180
181 async def acquire_write(
182 self, timeout: float | None = None, *, blocking: bool | None = None
183 ) -> AsyncAcquireSoftReadWriteReturnProxy:
184 """
185 Acquire an exclusive write lock.
186
187 See :meth:`SoftReadWriteLock.acquire_write` for the writer-preferring semantics. The blocking work runs inside
188 ``run_in_executor``.
189
190 :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
191 :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
192
193 :returns: a proxy usable as an async context manager to release the lock
194
195 :raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if
196 this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called
197 :raises Timeout: if the lock cannot be acquired within *timeout* seconds
198
199 """
200 self._raise_if_inherited()
201 await self._run_acquire(functools.partial(self._lock.acquire_write, timeout, blocking=blocking))
202 return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
203
204 async def release(self, *, force: bool = False) -> None:
205 """
206 Release one level of the current lock.
207
208 :param force: if ``True``, release the lock completely regardless of the current lock level
209
210 :raises RuntimeError: if no lock is currently held and *force* is ``False``
211
212 """
213 if self._creator_pid == os.getpid():
214 await self._run(self._lock.release, force=force)
215
216 async def close(self) -> None:
217 """Release any held lock and release the underlying filesystem resources. Idempotent."""
218 if self._creator_pid == os.getpid():
219 await self._run(self._lock.close)
220
221 def _raise_if_inherited(self) -> None:
222 if self._creator_pid != os.getpid(): # pragma: forked child
223 msg = f"AsyncSoftReadWriteLock on {self.lock_file} was inherited across fork; construct a new instance"
224 raise RuntimeError(msg)
225
226 async def _run_acquire(self, acquire: Callable[[], AcquireReturnProxy]) -> None:
227 # run_in_executor cannot recall work the pool already started, so canceling the caller does not stop the sync
228 # acquire: it still commits its claim, sets the hold, and starts the heartbeat, which keeps the record fresh
229 # forever so no peer on any host can evict it as stale. Wait the submitted call out and hand the claim back,
230 # the way AsyncReadWriteLock does.
231 acquire_future = self._submit(acquire)
232 try:
233 await _wait_until_done(acquire_future)
234 except asyncio.CancelledError as cancellation:
235 try:
236 await _drain_future(acquire_future)
237 except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
238 _raise_cancelled_error(cancellation, error)
239 try:
240 await _drain_future(self._submit(self._lock.release))
241 except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
242 _raise_cancelled_error(cancellation, error)
243 raise
244 _future_result(acquire_future)
245
246 async def _run(self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R:
247 # A canceled release or close is already running on the pool thread; drain it so its outcome is observed
248 # instead of finishing unwatched, then let the cancellation through.
249 future = self._submit(func, *args, **kwargs)
250 try:
251 await _wait_until_done(future)
252 except asyncio.CancelledError as cancellation:
253 try:
254 await _drain_future(future)
255 except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
256 _raise_cancelled_error(cancellation, error)
257 raise
258 return _future_result(future)
259
260 def _submit(
261 self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs
262 ) -> asyncio.Future[_BackendOutcome[_R]]:
263 loop = self._loop or asyncio.get_running_loop()
264 return loop.run_in_executor(self._executor, _capture_call, functools.partial(func, *args, **kwargs))
265
266
267 class AsyncAcquireSoftReadWriteReturnProxy:
268 """Async context-aware object that releases an :class:`AsyncSoftReadWriteLock` on exit."""
269
270 def __init__(self, lock: AsyncSoftReadWriteLock) -> None:
271 self.lock = lock
272
273 async def __aenter__(self) -> AsyncSoftReadWriteLock:
274 return self.lock
275
276 async def __aexit__(
277 self,
278 exc_type: type[BaseException] | None,
279 exc_value: BaseException | None,
280 traceback: TracebackType | None,
281 ) -> None:
282 await self.lock.release()
283
284
285 __all__ = [
286 "AsyncAcquireSoftReadWriteReturnProxy",
287 "AsyncSoftReadWriteLock",
288 ]