Debian Codegraph @

src/filelock/asyncio.py

raw
1 """An asyncio-based implementation of the file lock."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import contextlib
7 import logging
8 import os
9 import time
10 from dataclasses import dataclass
11 from inspect import iscoroutinefunction
12 from threading import local
13 from typing import TYPE_CHECKING, Final, NoReturn, TypeVar, cast
14
15 from ._api import (
16 _UNSET_FILE_MODE,
17 BaseFileLock,
18 CloseErrorPolicy,
19 ContextErrorPolicy,
20 FileLockContext,
21 FileLockMeta,
22 _append_exception_context,
23 _canonical,
24 _ExtraValue,
25 _fork_transition,
26 _grouped_errors,
27 _raise_body_and_release,
28 _raise_chained_errors,
29 _raise_cleanup_errors,
30 _raise_grouped_errors,
31 _register_fork_object,
32 _resolve_poll_interval,
33 )
34 from ._async import (
35 _AsyncTransitionGate,
36 _AsyncTransitionUnavailableError,
37 _BackendOutcome,
38 _capture_awaitable,
39 _capture_call,
40 _drain_future,
41 _future_result,
42 _wait_until_done,
43 )
44 from ._error import Timeout
45 from ._lease import SoftFileLease
46 from ._soft import SoftFileLock
47 from ._strict import StrictSoftFileLock
48 from ._unix import UnixFileLock
49 from ._windows import WindowsFileLock
50
51 if TYPE_CHECKING:
52 import sys
53 from collections.abc import Awaitable, Callable, Coroutine, Hashable
54 from concurrent import futures
55 from types import TracebackType
56
57 if sys.version_info >= (3, 11): # pragma: no cover (py311+)
58 from typing import Self
59 else: # pragma: no cover (<py311)
60 from typing_extensions import Self
61
62
63 _LOGGER: Final[logging.Logger] = logging.getLogger("filelock")
64 _ASYNC_RELEASE_CANCELLATION_ERRORS: Final[str] = "lock release cancellation and backend release both failed"
65 _ASYNC_CONTEXT_RELEASE_ERRORS: Final[str] = "context body, release cancellation, and backend release failed"
66 _ASYNC_RELEASE_CANCELLATION_MARKER_ATTR: Final[str] = "_filelock_async_release_cancellation"
67 _ASYNC_RELEASE_CANCELLATION_MARKER: Final[list[None]] = []
68
69 _AT = TypeVar("_AT", bound="BaseAsyncFileLock")
70
71
72 class AsyncFileLockMeta(FileLockMeta):
73 def __call__( # ruff:ignore[too-many-arguments] # forwards the public constructor's documented parameters
74 cls: type[_AT], # ruff:ignore[invalid-first-argument-name-for-method] # metaclass __call__ receives the class being constructed
75 lock_file: str | os.PathLike[str],
76 timeout: float = -1,
77 mode: int = _UNSET_FILE_MODE,
78 thread_local: bool = False, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility
79 *,
80 blocking: bool = True,
81 is_singleton: bool = False,
82 poll_interval: float = 0.05,
83 lifetime: float | None = None,
84 context_error_policy: ContextErrorPolicy = "chain",
85 close_error_policy: CloseErrorPolicy = "default",
86 fallback_to_soft: bool = True,
87 preserve_lock_file: bool = False,
88 on_acquired: Callable[[int], None] | None = None,
89 loop: asyncio.AbstractEventLoop | None = None,
90 run_in_executor: bool = True,
91 executor: futures.Executor | None = None,
92 **kwargs: _ExtraValue,
93 ) -> _AT:
94 if thread_local and run_in_executor:
95 msg = "run_in_executor is not supported when thread_local is True"
96 raise ValueError(msg)
97 return super().__call__( # a subclass may add options of its own, as AsyncSoftFileLease does
98 **kwargs,
99 lock_file=lock_file,
100 timeout=timeout,
101 mode=mode,
102 thread_local=thread_local,
103 blocking=blocking,
104 is_singleton=is_singleton,
105 poll_interval=poll_interval,
106 lifetime=lifetime,
107 context_error_policy=context_error_policy,
108 close_error_policy=close_error_policy,
109 fallback_to_soft=fallback_to_soft,
110 preserve_lock_file=preserve_lock_file,
111 on_acquired=on_acquired,
112 loop=loop,
113 run_in_executor=run_in_executor,
114 executor=executor,
115 )
116
117
118 class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
119 """
120 Base class for asynchronous file locks.
121
122 .. versionadded:: 3.15.0
123
124 """
125
126 _deadlock_holder_desc: str = "BaseAsyncFileLock instance in this task"
127 _constructor_lifetime_warning_stacklevel: int = 4
128
129 @staticmethod
130 def _deadlock_scope() -> Hashable | None:
131 # One event loop thread runs every task, so a thread-scoped registry cannot tell a same-task reacquire
132 # (a real deadlock: the polling task never reaches its own release) from another task queuing behind the
133 # holder (no deadlock: each poll yields, so the holder runs on and releases). Only the first may fail
134 # fast, so scope holders to the task.
135 return asyncio.current_task()
136
137 def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option
138 self,
139 lock_file: str | os.PathLike[str],
140 timeout: float = -1,
141 mode: int = _UNSET_FILE_MODE,
142 thread_local: bool = False, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility
143 *,
144 blocking: bool = True,
145 is_singleton: bool = False,
146 poll_interval: float = 0.05,
147 lifetime: float | None = None,
148 context_error_policy: ContextErrorPolicy = "chain",
149 close_error_policy: CloseErrorPolicy = "default",
150 fallback_to_soft: bool = True,
151 preserve_lock_file: bool = False,
152 on_acquired: Callable[[int], None] | None = None,
153 loop: asyncio.AbstractEventLoop | None = None,
154 run_in_executor: bool = True,
155 executor: futures.Executor | None = None,
156 ) -> None:
157 """
158 Create a new lock object.
159
160 :param lock_file: path to the file
161 :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the
162 acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a
163 negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
164 :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and
165 default ACLs, preserving POSIX default ACL inheritance in shared directories.
166 :param thread_local: Whether this object's internal context should be thread local or not. If this is set to
167 ``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the
168 lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``,
169 ``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change
170 the value seen by another thread; threads that did not perform the write continue to see the value supplied
171 at construction time. ``mode`` has no setter, so construction is the only place it is ever set. If you need
172 configuration values to be visible across threads, construct the lock with ``thread_local=False``.
173 :param blocking: whether the lock should be blocking or not
174 :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock
175 file. This is useful if you want to use the lock object for reentrant locking without needing to pass the
176 same object around.
177 :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value
178 in the acquire method, if no poll_interval value (``None``) is given.
179 :param lifetime: for :class:`AsyncSoftFileLock`, the age in seconds after which a waiting process may delete
180 the marker, even while its holder remains alive. This legacy expiry mode does not provide strict mutual
181 exclusion. ``None`` (the default) disables age-based expiry. Native OS locks (:class:`AsyncFileLock`)
182 cannot be revoked by file age and ignore a non-``None`` ``lifetime`` with a warning.
183 :param context_error_policy: how a context manager reconciles a failure in its body with a failure while
184 releasing on exit. ``"chain"`` (the default) keeps Python's behavior: the release error propagates with the
185 body error in its ``__context__``. ``"group"`` raises a :class:`BaseExceptionGroup` holding the body error
186 first and the release error second, so neither hides the other.
187 :param close_error_policy: for native locks (:class:`AsyncFileLock`), what to do with an ``os.close`` failure
188 after the OS unlock has already committed. ``"default"`` keeps each platform's historical behavior,
189 ``"raise"`` always propagates the ``OSError``, and ``"suppress"`` always ignores it.
190 :param fallback_to_soft: for :class:`AsyncFileLock`, whether to fall back to soft existence locking when
191 ``flock`` returns ``ENOSYS``. ``True`` (default) keeps the fallback; ``False`` propagates the error.
192 :param preserve_lock_file: for native locks (:class:`AsyncFileLock`), whether filelock promises not to unlink
193 the lock pathname on release. ``False`` (default) keeps each backend's cleanup; ``True`` keeps a stable file
194 identity (Windows skips its unlink, Unix refuses the ``ENOSYS`` soft fallback). :class:`AsyncSoftFileLock`
195 rejects ``True``.
196 :param on_acquired: for native locks (:class:`AsyncFileLock`), a callable invoked with the borrowed lock
197 descriptor once per physical acquisition, after the lock is held but before
198 :meth:`~BaseAsyncFileLock.acquire` returns. With ``run_in_executor=True`` (the default) it runs in the
199 backend executor. It must not close or unlock the descriptor; a raise rolls the acquisition back.
200 :class:`AsyncSoftFileLock` rejects it.
201 :param loop: The event loop to use. If not specified, the running event loop will be used.
202 :param run_in_executor: If this is set to ``True`` then the lock will be acquired in an executor.
203 :param executor: The executor to use. If not specified, the default executor will be used.
204
205 """
206 self._creator_pid = os.getpid()
207 self._is_thread_local = thread_local
208 self._is_singleton = is_singleton
209 self._context_error_policy = context_error_policy # already validated by the metaclass
210 self._close_error_policy = close_error_policy # already validated by the metaclass
211 self._fallback_to_soft = fallback_to_soft
212 self._preserve_lock_file = preserve_lock_file # already validated by the metaclass
213 self._on_acquired = on_acquired # already validated by the metaclass
214 self._transition_gate: Final[_AsyncTransitionGate] = _AsyncTransitionGate()
215
216 self._context: AsyncFileLockContext = (AsyncThreadLocalFileContext if thread_local else AsyncFileLockContext)(
217 lock_file=os.fspath(lock_file),
218 timeout=timeout,
219 mode=mode,
220 blocking=blocking,
221 poll_interval=poll_interval,
222 lifetime=lifetime,
223 loop=loop,
224 run_in_executor=run_in_executor,
225 executor=executor,
226 )
227 _register_fork_object(self)
228
229 @property
230 def run_in_executor(self) -> bool:
231 """Whether run in executor."""
232 return self._context.run_in_executor
233
234 @property
235 def executor(self) -> futures.Executor | None:
236 """The executor."""
237 return self._context.executor
238
239 @executor.setter
240 def executor(self, value: futures.Executor | None) -> None: # pragma: no cover
241 """
242 Change the executor.
243
244 :param futures.Executor | None value: the new executor or ``None``
245
246 """
247 self._context.executor = value
248
249 @property
250 def loop(self) -> asyncio.AbstractEventLoop | None:
251 """The event loop."""
252 return self._context.loop
253
254 async def acquire( # ty: ignore[invalid-method-override]
255 self,
256 timeout: float | None = None,
257 poll_interval: float | None = None,
258 *,
259 blocking: bool | None = None,
260 cancel_check: Callable[[], bool] | None = None,
261 ) -> AsyncAcquireReturnProxy:
262 """
263 Try to acquire the file lock.
264
265 :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default
266 :attr:`~BaseFileLock.timeout` is and if ``timeout < 0``, there is no timeout and this method will block
267 until the lock could be acquired
268 :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default
269 :attr:`~BaseFileLock.poll_interval`
270 :param blocking: whether to retry until this call holds the lock or the timeout expires, ``None`` means use
271 the default :attr:`~BaseFileLock.blocking`. ``False`` makes one attempt and raises :class:`~Timeout` on
272 failure.
273 :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll
274 iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.
275
276 :returns: a context object that will unlock the file when the context is exited
277
278 :raises Timeout: if fails to acquire lock within the timeout period
279
280 .. code-block:: python
281
282 # You can use this method in the context manager (recommended)
283 with lock.acquire():
284 pass
285
286 # Or use an equivalent try-finally construct:
287 lock.acquire()
288 try:
289 pass
290 finally:
291 lock.release()
292
293 """
294 self._raise_if_inherited()
295 if timeout is None:
296 timeout = self._context.timeout
297
298 if blocking is None:
299 blocking = self._context.blocking
300
301 if poll_interval is None:
302 poll_interval = self._context.poll_interval
303 poll_interval = _resolve_poll_interval(poll_interval)
304
305 start_time = time.perf_counter()
306 try:
307 return await self._acquire_with_admission(
308 blocking=blocking,
309 cancel_check=cancel_check,
310 timeout=timeout,
311 poll_interval=poll_interval,
312 start_time=start_time,
313 )
314 except _AsyncTransitionUnavailableError:
315 raise Timeout(self.lock_file) from None
316
317 async def _acquire_with_admission(
318 self,
319 *,
320 blocking: bool,
321 cancel_check: Callable[[], bool] | None,
322 timeout: float,
323 poll_interval: float,
324 start_time: float,
325 ) -> AsyncAcquireReturnProxy:
326 async with self._transition_gate.hold_for_acquire(
327 blocking=blocking,
328 cancel_check=cancel_check,
329 deadline=None if timeout < 0 else start_time + timeout,
330 poll_interval=poll_interval,
331 ):
332 # A canceled provisional acquire must finish rollback before another caller can claim its descriptor.
333 canonical = _canonical(self.lock_file)
334 self._context.lock_counter += 1
335 self._raise_if_would_deadlock(canonical, timeout=timeout, blocking=blocking)
336 self._context.claim_root = canonical
337 try:
338 await self._async_poll_until_acquired(
339 blocking=blocking,
340 cancel_check=cancel_check,
341 timeout=timeout,
342 poll_interval=poll_interval,
343 start_time=start_time,
344 )
345 except BaseException:
346 self._reconcile_failed_acquire(canonical)
347 raise
348 finally:
349 self._context.claim_root = None
350 self._commit_acquire(canonical)
351 return AsyncAcquireReturnProxy(lock=self)
352
353 async def _async_poll_until_acquired(
354 self,
355 *,
356 blocking: bool,
357 cancel_check: Callable[[], bool] | None,
358 timeout: float,
359 poll_interval: float,
360 start_time: float,
361 ) -> None:
362 lock_id = id(self)
363 lock_filename = self.lock_file
364 while True:
365 self._raise_if_inherited()
366 if not self.is_locked:
367 self._try_break_expired_lock()
368 _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
369 await self._run_acquire_attempt()
370 self._raise_if_inherited()
371 if self.is_locked:
372 _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
373 return
374 if self._check_give_up(
375 blocking=blocking,
376 cancel_check=cancel_check,
377 timeout=timeout,
378 start_time=start_time,
379 ):
380 raise Timeout(lock_filename)
381 _LOGGER.debug("Lock %s not acquired on %s, waiting %s seconds ...", lock_id, lock_filename, poll_interval)
382 await asyncio.sleep(poll_interval)
383
384 async def _run_acquire_attempt(self) -> None:
385 acquire_future = self._start_internal_method(
386 self._acquire_with_fork_tracking_async
387 if iscoroutinefunction(self._acquire)
388 else self._acquire_with_fork_tracking
389 )
390 try:
391 await _wait_until_done(acquire_future)
392 except asyncio.CancelledError as cancellation:
393 acquire_error: BaseException | None = None
394 try:
395 await _drain_future(acquire_future)
396 except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
397 acquire_error = error
398
399 rollback_error: BaseException | None = None
400 if self.is_locked:
401 try:
402 await _drain_future(self._start_tracked_release())
403 except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
404 rollback_error = error
405
406 if acquire_error is not None:
407 if rollback_error is not None: # pragma: needs fcntl
408 self._raise_cancelled_errors(
409 "lock acquisition cancellation, backend attempt, and rollback failed",
410 cancellation,
411 acquire_error,
412 rollback_error,
413 )
414 self._raise_cancelled_errors(
415 "lock acquisition cancellation and backend attempt both failed", cancellation, acquire_error
416 )
417 if rollback_error is not None:
418 self._raise_cancelled_errors(
419 "lock acquisition cancellation and rollback both failed", cancellation, rollback_error
420 )
421 raise
422 try:
423 _future_result(acquire_future)
424 except asyncio.CancelledError as acquire_error:
425 await self._rollback_backend_cancelled_acquire(acquire_error)
426
427 async def _rollback_backend_cancelled_acquire(self, acquire_error: asyncio.CancelledError) -> NoReturn:
428 if self.is_locked:
429 try:
430 await _drain_future(self._start_tracked_release())
431 except BaseException as rollback_error: # ruff:ignore[blind-except] # both backend errors must surface
432 self._raise_acquire_rollback_errors(acquire_error, rollback_error)
433 raise acquire_error
434
435 def _raise_acquire_rollback_errors(self, acquire_error: BaseException, rollback_error: BaseException) -> NoReturn:
436 if self._context_error_policy == "group":
437 _raise_grouped_errors("lock acquisition backend and rollback both failed", acquire_error, rollback_error)
438 _raise_chained_errors(acquire_error, rollback_error)
439
440 def _raise_cancelled_errors(
441 self,
442 message: str,
443 cancellation: asyncio.CancelledError,
444 first_error: BaseException,
445 second_error: BaseException | None = None,
446 ) -> NoReturn:
447 if self._context_error_policy == "group":
448 marker = (
449 (_ASYNC_RELEASE_CANCELLATION_MARKER_ATTR, _ASYNC_RELEASE_CANCELLATION_MARKER)
450 if message == _ASYNC_RELEASE_CANCELLATION_ERRORS
451 else None
452 )
453 if second_error is None:
454 _raise_grouped_errors(message, cancellation, first_error, marker=marker)
455 _raise_grouped_errors(message, cancellation, first_error, second_error, marker=marker)
456 if (context := first_error.__context__) is not None and context is not cancellation:
457 if (cancellation_context := cancellation.__context__) is not None:
458 _append_exception_context(context, cancellation_context)
459 cancellation.__context__ = context
460 first_error.__context__ = cancellation
461 _raise_chained_errors(first_error, second_error)
462
463 async def release(self, force: bool = False) -> None: # ty: ignore[invalid-method-override] # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility
464 """
465 Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file
466 itself may be deleted automatically, the behavior is platform-specific.
467
468 :param force: If true, the lock counter is ignored and the lock is released in every case.
469
470 """
471 if self._creator_pid != os.getpid() or not self.is_locked:
472 return
473 async with self._transition_gate.hold():
474 await self._release_serialized(force=force)
475
476 async def _release_serialized(self, *, force: bool) -> None:
477 if not self.is_locked:
478 return
479 if not force and self._context.lock_counter > 1:
480 self._context.lock_counter -= 1
481 return
482
483 lock_id, lock_filename = id(self), self.lock_file
484 _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
485 release_future = self._start_tracked_release()
486 try:
487 await _wait_until_done(release_future)
488 except asyncio.CancelledError as cancellation:
489 try:
490 await _drain_future(release_future)
491 except BaseException as release_error: # ruff:ignore[blind-except] # cancellation and backend failure must both surface
492 self._commit_release_if_released()
493 self._raise_cancelled_errors(_ASYNC_RELEASE_CANCELLATION_ERRORS, cancellation, release_error)
494 self._commit_release()
495 raise
496 try:
497 _future_result(release_future)
498 except BaseException: # state follows the backend for control-flow exceptions too
499 self._commit_release_if_released()
500 raise
501 self._commit_release()
502 _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
503
504 def _commit_release_if_released(self) -> None:
505 # Commit only when the backend actually unlocked (close or unlink failed after the OS unlock). If the lock is
506 # still held, keep the counter so a later release can retry.
507 if not self.is_locked:
508 self._commit_release()
509
510 def _start_internal_method(
511 self, method: Callable[[], None] | Callable[[], Coroutine[None, None, None]]
512 ) -> asyncio.Future[_BackendOutcome[None]]:
513 if iscoroutinefunction(method):
514 return asyncio.create_task(_capture_awaitable(cast("Callable[[], Coroutine[None, None, None]]", method)()))
515 loop = asyncio.get_running_loop()
516 sync_method = cast("Callable[[], None]", method)
517 if self.run_in_executor:
518 return loop.run_in_executor(self.executor, _capture_call, sync_method)
519 future: asyncio.Future[_BackendOutcome[None]] = loop.create_future()
520 future.set_result(_capture_call(sync_method))
521 return future
522
523 def _start_tracked_release(self) -> asyncio.Future[_BackendOutcome[None]]:
524 return self._start_internal_method(
525 self._release_with_fork_tracking_async
526 if iscoroutinefunction(self._release)
527 else self._release_with_fork_tracking
528 )
529
530 async def _acquire_with_fork_tracking_async(self) -> None:
531 with _fork_transition(self):
532 try:
533 await cast("Callable[[], Awaitable[None]]", self._acquire)()
534 except BaseException as acquisition_error:
535 await self._rollback_failed_acquire_async(acquisition_error)
536 raise
537 try:
538 self._register_context_descriptor()
539 except BaseException as registration_error: # cancellation must roll back the descriptor
540 await self._rollback_failed_registration_async(registration_error)
541 raise
542 if self.is_locked:
543 await self._invoke_on_acquired_async()
544
545 async def _rollback_failed_acquire_async(self, acquisition_error: BaseException) -> None:
546 if not self.is_locked:
547 return
548 registration_error: BaseException | None = None
549 tracking_error: BaseException | None = None
550 try:
551 self._register_context_descriptor()
552 except BaseException as error: # ruff:ignore[blind-except] # preserve registration and acquisition failures
553 registration_error = error
554 try:
555 # Rollback may fail too; retain the fd so a child can close it without another identity probe.
556 self._register_unverified_context_descriptor()
557 except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback
558 tracking_error = error
559 try:
560 await _drain_future(self._start_tracked_release())
561 except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and acquisition failures
562 if registration_error is None and tracking_error is None:
563 self._raise_acquire_rollback_errors(acquisition_error, rollback_error)
564 _raise_cleanup_errors(
565 "lock acquisition cleanup failed",
566 acquisition_error,
567 registration_error,
568 tracking_error,
569 rollback_error,
570 )
571 if registration_error is not None:
572 _raise_cleanup_errors(
573 "lock acquisition cleanup failed", acquisition_error, registration_error, tracking_error
574 )
575
576 async def _rollback_failed_registration_async(self, registration_error: BaseException) -> None:
577 tracking_error: BaseException | None = None
578 try:
579 # Rollback may fail too; retain the fd so a child can close it without another identity probe.
580 self._register_unverified_context_descriptor()
581 except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback
582 tracking_error = error
583 try:
584 await _drain_future(self._start_tracked_release())
585 except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and registration failures
586 _raise_cleanup_errors(
587 "descriptor registration cleanup failed", registration_error, tracking_error, rollback_error
588 )
589 if tracking_error is not None: # pragma: no cover - requires failed in-memory fallback
590 _raise_cleanup_errors("descriptor registration cleanup failed", registration_error, tracking_error)
591
592 async def _invoke_on_acquired_async(self) -> None:
593 if self._on_acquired is None or self._context.lock_counter != 1:
594 return
595 try:
596 self._on_acquired(cast("int", self._context.lock_file_fd))
597 except BaseException as callback_error: # caller control-flow errors must release the lock
598 callback_context = callback_error.__context__
599 try:
600 await _drain_future(self._start_tracked_release())
601 except BaseException as release_error: # ruff:ignore[blind-except] # both errors surface via the group below
602 _raise_body_and_release(callback_error, release_error)
603 callback_error.__context__ = callback_context
604 raise
605
606 async def _release_with_fork_tracking_async(self) -> None:
607 with _fork_transition(self):
608 try:
609 await cast("Callable[[], Awaitable[None]]", self._release)()
610 finally:
611 self._unregister_released_descriptor()
612
613 def __enter__(self) -> NoReturn:
614 """Sync context manager entry is not supported because lock acquisition is a coroutine."""
615 msg = "Use `async with`: acquire/release are coroutines and cannot be awaited in a sync context manager."
616 raise NotImplementedError(msg)
617
618 def __exit__(
619 self,
620 exc_type: type[BaseException] | None,
621 exc_value: BaseException | None,
622 traceback: TracebackType | None,
623 ) -> None:
624 """Sync context manager exit is not supported because lock release is a coroutine."""
625 msg = "Use `async with`: acquire/release are coroutines and cannot be awaited in a sync context manager."
626 raise NotImplementedError(msg)
627
628 async def __aenter__(self) -> Self:
629 """
630 Acquire the lock.
631
632 :returns: the lock object
633
634 """
635 await self.acquire()
636 return self
637
638 async def __aexit__(
639 self,
640 exc_type: type[BaseException] | None,
641 exc_value: BaseException | None,
642 traceback: TracebackType | None,
643 ) -> None:
644 """
645 Release the lock, reconciling a release failure with any body failure per :attr:`context_error_policy`.
646
647 :param exc_type: the exception type if raised
648 :param exc_value: the exception value if raised
649 :param traceback: the exception traceback if raised
650
651 """
652 await self._release_in_context(exc_value)
653
654 async def _release_in_context( # ty: ignore[invalid-method-override]
655 self, body_error: BaseException | None
656 ) -> None:
657 # The async counterpart of BaseFileLock._release_in_context: await release, then apply the same policy.
658 try:
659 await self.release()
660 except BaseException as release_error:
661 if body_error is None:
662 raise
663 if self._context_error_policy == "chain":
664 _append_exception_context(release_error, body_error)
665 raise
666 if (
667 errors := _grouped_errors(
668 release_error,
669 _ASYNC_RELEASE_CANCELLATION_ERRORS,
670 (_ASYNC_RELEASE_CANCELLATION_MARKER_ATTR, _ASYNC_RELEASE_CANCELLATION_MARKER),
671 )
672 ) is not None:
673 match errors:
674 # The marker is only ever set on a (CancelledError, backend_error) pair, so this always matches.
675 case (asyncio.CancelledError() as cancellation, backend_error): # pragma: no branch
676 _raise_grouped_errors(_ASYNC_CONTEXT_RELEASE_ERRORS, body_error, cancellation, backend_error)
677 _raise_body_and_release(body_error, release_error)
678
679 def __del__(self) -> None:
680 """Release on deletion; safe to call during GC even when no event loop is running."""
681 if vars(self).get("_creator_pid") != os.getpid():
682 return # pragma: forked child
683 with contextlib.suppress(Exception):
684 try:
685 loop = asyncio.get_running_loop()
686 except RuntimeError:
687 loop = self._context.loop if self._context.loop and not self._context.loop.is_closed() else None
688 if loop is None:
689 return
690 if not loop.is_running(): # pragma: no cover
691 loop.run_until_complete(self.release(force=True))
692 else:
693 loop.create_task(self.release(force=True))
694
695
696 @dataclass
697 class AsyncFileLockContext(FileLockContext):
698 """A dataclass which holds the context for a ``BaseAsyncFileLock`` object."""
699
700 #: Whether run in executor
701 run_in_executor: bool = True
702
703 #: The executor
704 executor: futures.Executor | None = None
705
706 #: The loop
707 loop: asyncio.AbstractEventLoop | None = None
708
709
710 class AsyncThreadLocalFileContext(AsyncFileLockContext, local):
711 """A thread local version of the ``FileLockContext`` class."""
712
713
714 class AsyncAcquireReturnProxy:
715 """A context-aware object that will release the lock file when exiting."""
716
717 def __init__(self, lock: BaseAsyncFileLock) -> None: # ruff:ignore[undocumented-public-init] # trivial release-on-exit proxy
718 self.lock = lock
719
720 async def __aenter__(self) -> BaseAsyncFileLock: # ruff:ignore[undocumented-magic-method] # returns the wrapped lock
721 return self.lock
722
723 async def __aexit__( # ruff:ignore[undocumented-magic-method] # releases the wrapped lock on exit
724 self,
725 exc_type: type[BaseException] | None,
726 exc_value: BaseException | None,
727 traceback: TracebackType | None,
728 ) -> None:
729 await self.lock._release_in_context(exc_value) # ruff:ignore[private-member-access] # releases the wrapped lock's context
730
731
732 class AsyncSoftFileLock(SoftFileLock, BaseAsyncFileLock):
733 """Simply watches the existence of the lock file."""
734
735 _lifetime_replacements: tuple[str, str] | None = ("AsyncStrictSoftFileLock", "AsyncSoftFileLease")
736
737
738 class AsyncStrictSoftFileLock(StrictSoftFileLock, BaseAsyncFileLock):
739 """Run strict owner-claim locking without blocking the event loop."""
740
741
742 class AsyncSoftFileLease(SoftFileLease, BaseAsyncFileLock):
743 """Existence lock whose claim expires, so a peer may take it while the previous holder still runs."""
744
745
746 class AsyncUnixFileLock(UnixFileLock, BaseAsyncFileLock):
747 """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
748
749
750 class AsyncWindowsFileLock(WindowsFileLock, BaseAsyncFileLock):
751 """Uses the :func:`msvcrt.locking` to hard lock the lock file on windows systems."""
752
753
754 __all__ = [
755 "AsyncAcquireReturnProxy",
756 "AsyncSoftFileLease",
757 "AsyncSoftFileLock",
758 "AsyncStrictSoftFileLock",
759 "AsyncUnixFileLock",
760 "AsyncWindowsFileLock",
761 "BaseAsyncFileLock",
762 ]