Voice et bot modif
This commit is contained in:
parent
189d56026b
commit
7333a22bcd
10774 changed files with 634644 additions and 933308 deletions
|
|
@ -10,9 +10,9 @@ import time
|
|||
from dataclasses import dataclass
|
||||
from inspect import iscoroutinefunction
|
||||
from threading import local
|
||||
from typing import TYPE_CHECKING, Any, NoReturn, cast
|
||||
from typing import TYPE_CHECKING, Any, NoReturn, TypeVar
|
||||
|
||||
from ._api import BaseFileLock, FileLockContext, FileLockMeta
|
||||
from ._api import _UNSET_FILE_MODE, BaseFileLock, FileLockContext, FileLockMeta
|
||||
from ._error import Timeout
|
||||
from ._soft import SoftFileLock
|
||||
from ._unix import UnixFileLock
|
||||
|
|
@ -69,49 +69,62 @@ class AsyncAcquireReturnProxy:
|
|||
await self.lock.release()
|
||||
|
||||
|
||||
_AT = TypeVar("_AT", bound="BaseAsyncFileLock")
|
||||
|
||||
|
||||
class AsyncFileLockMeta(FileLockMeta):
|
||||
def __call__( # type: ignore[override] # noqa: PLR0913
|
||||
cls, # noqa: N805
|
||||
def __call__( # ty: ignore[invalid-method-override] # noqa: PLR0913
|
||||
cls: type[_AT], # noqa: N805
|
||||
lock_file: str | os.PathLike[str],
|
||||
timeout: float = -1,
|
||||
mode: int = 0o644,
|
||||
mode: int = _UNSET_FILE_MODE,
|
||||
thread_local: bool = False, # noqa: FBT001, FBT002
|
||||
*,
|
||||
blocking: bool = True,
|
||||
is_singleton: bool = False,
|
||||
poll_interval: float = 0.05,
|
||||
lifetime: float | None = None,
|
||||
loop: asyncio.AbstractEventLoop | None = None,
|
||||
run_in_executor: bool = True,
|
||||
executor: futures.Executor | None = None,
|
||||
) -> BaseAsyncFileLock:
|
||||
) -> _AT:
|
||||
if thread_local and run_in_executor:
|
||||
msg = "run_in_executor is not supported when thread_local is True"
|
||||
raise ValueError(msg)
|
||||
instance = super().__call__(
|
||||
return super().__call__(
|
||||
lock_file=lock_file,
|
||||
timeout=timeout,
|
||||
mode=mode,
|
||||
thread_local=thread_local,
|
||||
blocking=blocking,
|
||||
is_singleton=is_singleton,
|
||||
poll_interval=poll_interval,
|
||||
lifetime=lifetime,
|
||||
loop=loop,
|
||||
run_in_executor=run_in_executor,
|
||||
executor=executor,
|
||||
)
|
||||
return cast("BaseAsyncFileLock", instance)
|
||||
|
||||
|
||||
class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
|
||||
"""Base class for asynchronous file locks."""
|
||||
"""
|
||||
Base class for asynchronous file locks.
|
||||
|
||||
.. versionadded:: 3.15.0
|
||||
|
||||
"""
|
||||
|
||||
def __init__( # noqa: PLR0913
|
||||
self,
|
||||
lock_file: str | os.PathLike[str],
|
||||
timeout: float = -1,
|
||||
mode: int = 0o644,
|
||||
mode: int = _UNSET_FILE_MODE,
|
||||
thread_local: bool = False, # noqa: FBT001, FBT002
|
||||
*,
|
||||
blocking: bool = True,
|
||||
is_singleton: bool = False,
|
||||
poll_interval: float = 0.05,
|
||||
lifetime: float | None = None,
|
||||
loop: asyncio.AbstractEventLoop | None = None,
|
||||
run_in_executor: bool = True,
|
||||
executor: futures.Executor | None = None,
|
||||
|
|
@ -120,16 +133,27 @@ class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
|
|||
Create a new lock object.
|
||||
|
||||
:param lock_file: path to the file
|
||||
:param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in \
|
||||
the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it \
|
||||
to a negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
|
||||
:param mode: file permissions for the lockfile
|
||||
:param thread_local: Whether this object's internal context should be thread local or not. If this is set to \
|
||||
``False`` then the lock will be reentrant across threads.
|
||||
:param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the
|
||||
acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a
|
||||
negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
|
||||
:param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and
|
||||
default ACLs, preserving POSIX default ACL inheritance in shared directories.
|
||||
:param thread_local: Whether this object's internal context should be thread local or not. If this is set to
|
||||
``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the
|
||||
lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``,
|
||||
``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change
|
||||
the value seen by another thread; threads that did not perform the write continue to see the value supplied
|
||||
at construction time. If you need configuration values to be visible across threads, construct the lock
|
||||
with ``thread_local=False``.
|
||||
:param blocking: whether the lock should be blocking or not
|
||||
:param is_singleton: If this is set to ``True`` then only one instance of this class will be created \
|
||||
per lock file. This is useful if you want to use the lock object for reentrant locking without needing \
|
||||
to pass the same object around.
|
||||
:param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock
|
||||
file. This is useful if you want to use the lock object for reentrant locking without needing to pass the
|
||||
same object around.
|
||||
:param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value
|
||||
in the acquire method, if no poll_interval value (``None``) is given.
|
||||
:param lifetime: maximum time in seconds a lock can be held before it is considered expired. When set, a waiting
|
||||
process will break a lock whose file modification time is older than ``lifetime`` seconds. ``None`` (the
|
||||
default) means locks never expire.
|
||||
:param loop: The event loop to use. If not specified, the running event loop will be used.
|
||||
:param run_in_executor: If this is set to ``True`` then the lock will be acquired in an executor.
|
||||
:param executor: The executor to use. If not specified, the default executor will be used.
|
||||
|
|
@ -145,6 +169,8 @@ class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
|
|||
"timeout": timeout,
|
||||
"mode": mode,
|
||||
"blocking": blocking,
|
||||
"poll_interval": poll_interval,
|
||||
"lifetime": lifetime,
|
||||
"loop": loop,
|
||||
"run_in_executor": run_in_executor,
|
||||
"executor": executor,
|
||||
|
|
@ -155,12 +181,12 @@ class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
|
|||
|
||||
@property
|
||||
def run_in_executor(self) -> bool:
|
||||
"""::return: whether run in executor."""
|
||||
""":returns: whether run in executor."""
|
||||
return self._context.run_in_executor
|
||||
|
||||
@property
|
||||
def executor(self) -> futures.Executor | None:
|
||||
"""::return: the executor."""
|
||||
""":returns: the executor."""
|
||||
return self._context.executor
|
||||
|
||||
@executor.setter
|
||||
|
|
@ -168,35 +194,40 @@ class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
|
|||
"""
|
||||
Change the executor.
|
||||
|
||||
:param value: the new executor or ``None``
|
||||
:type value: futures.Executor | None
|
||||
:param futures.Executor | None value: the new executor or ``None``
|
||||
|
||||
"""
|
||||
self._context.executor = value
|
||||
|
||||
@property
|
||||
def loop(self) -> asyncio.AbstractEventLoop | None:
|
||||
"""::return: the event loop."""
|
||||
""":returns: the event loop."""
|
||||
return self._context.loop
|
||||
|
||||
async def acquire( # type: ignore[override]
|
||||
async def acquire( # ty: ignore[invalid-method-override]
|
||||
self,
|
||||
timeout: float | None = None,
|
||||
poll_interval: float = 0.05,
|
||||
poll_interval: float | None = None,
|
||||
*,
|
||||
blocking: bool | None = None,
|
||||
cancel_check: Callable[[], bool] | None = None,
|
||||
) -> AsyncAcquireReturnProxy:
|
||||
"""
|
||||
Try to acquire the file lock.
|
||||
|
||||
:param timeout: maximum wait time for acquiring the lock, ``None`` means use the default
|
||||
:attr:`~BaseFileLock.timeout` is and if ``timeout < 0``, there is no timeout and
|
||||
this method will block until the lock could be acquired
|
||||
:param poll_interval: interval of trying to acquire the lock file
|
||||
:attr:`~BaseFileLock.timeout` is and if ``timeout < 0``, there is no timeout and this method will block
|
||||
until the lock could be acquired
|
||||
:param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default
|
||||
:attr:`~BaseFileLock.poll_interval`
|
||||
:param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
|
||||
first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
|
||||
first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
|
||||
:param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll
|
||||
iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.
|
||||
|
||||
:returns: a context object that will unlock the file when the context is exited
|
||||
|
||||
:raises Timeout: if fails to acquire lock within the timeout period
|
||||
:return: a context object that will unlock the file when the context is exited
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
|
@ -219,40 +250,64 @@ class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
|
|||
if blocking is None:
|
||||
blocking = self._context.blocking
|
||||
|
||||
if poll_interval is None:
|
||||
poll_interval = self._context.poll_interval
|
||||
|
||||
# Increment the number right at the beginning. We can still undo it, if something fails.
|
||||
self._context.lock_counter += 1
|
||||
|
||||
lock_id = id(self)
|
||||
lock_filename = self.lock_file
|
||||
start_time = time.perf_counter()
|
||||
try:
|
||||
while True:
|
||||
if not self.is_locked:
|
||||
_LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
|
||||
await self._run_internal_method(self._acquire)
|
||||
if self.is_locked:
|
||||
_LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
|
||||
break
|
||||
if blocking is False:
|
||||
_LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
|
||||
raise Timeout(lock_filename) # noqa: TRY301
|
||||
if 0 <= timeout < time.perf_counter() - start_time:
|
||||
_LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
|
||||
raise Timeout(lock_filename) # noqa: TRY301
|
||||
msg = "Lock %s not acquired on %s, waiting %s seconds ..."
|
||||
_LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
|
||||
await asyncio.sleep(poll_interval)
|
||||
await self._async_poll_until_acquired(
|
||||
blocking=blocking,
|
||||
cancel_check=cancel_check,
|
||||
timeout=timeout,
|
||||
poll_interval=poll_interval,
|
||||
start_time=start_time,
|
||||
)
|
||||
except BaseException: # Something did go wrong, so decrement the counter.
|
||||
self._context.lock_counter = max(0, self._context.lock_counter - 1)
|
||||
raise
|
||||
return AsyncAcquireReturnProxy(lock=self)
|
||||
|
||||
async def release(self, force: bool = False) -> None: # type: ignore[override] # noqa: FBT001, FBT002
|
||||
"""
|
||||
Releases the file lock. Please note, that the lock is only completely released, if the lock counter is 0.
|
||||
Also note, that the lock file itself is not automatically deleted.
|
||||
async def _async_poll_until_acquired(
|
||||
self,
|
||||
*,
|
||||
blocking: bool,
|
||||
cancel_check: Callable[[], bool] | None,
|
||||
timeout: float,
|
||||
poll_interval: float,
|
||||
start_time: float,
|
||||
) -> None:
|
||||
lock_id = id(self)
|
||||
lock_filename = self.lock_file
|
||||
while True:
|
||||
if not self.is_locked:
|
||||
self._try_break_expired_lock()
|
||||
_LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
|
||||
await self._run_internal_method(self._acquire)
|
||||
if self.is_locked:
|
||||
_LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
|
||||
return
|
||||
if self._check_give_up(
|
||||
lock_id,
|
||||
lock_filename,
|
||||
blocking=blocking,
|
||||
cancel_check=cancel_check,
|
||||
timeout=timeout,
|
||||
start_time=start_time,
|
||||
):
|
||||
raise Timeout(lock_filename)
|
||||
msg = "Lock %s not acquired on %s, waiting %s seconds ..."
|
||||
_LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
|
||||
await asyncio.sleep(poll_interval)
|
||||
|
||||
:param force: If true, the lock counter is ignored and the lock is released in every case/
|
||||
async def release(self, force: bool = False) -> None: # ty: ignore[invalid-method-override] # noqa: FBT001, FBT002
|
||||
"""
|
||||
Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file
|
||||
itself may be deleted automatically, the behavior is platform-specific.
|
||||
|
||||
:param force: If true, the lock counter is ignored and the lock is released in every case.
|
||||
|
||||
"""
|
||||
if self.is_locked:
|
||||
|
|
@ -270,28 +325,30 @@ class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
|
|||
if iscoroutinefunction(method):
|
||||
await method()
|
||||
elif self.run_in_executor:
|
||||
loop = self.loop or asyncio.get_running_loop()
|
||||
await loop.run_in_executor(self.executor, method)
|
||||
await asyncio.get_running_loop().run_in_executor(self.executor, method)
|
||||
else:
|
||||
method()
|
||||
|
||||
def __enter__(self) -> NoReturn:
|
||||
"""
|
||||
Replace old __enter__ method to avoid using it.
|
||||
"""Sync context manager entry is not supported because lock acquisition is a coroutine."""
|
||||
msg = "Use `async with` — acquire/release are coroutines and cannot be awaited in a sync context manager."
|
||||
raise NotImplementedError(msg)
|
||||
|
||||
NOTE: DO NOT USE `with` FOR ASYNCIO LOCKS, USE `async with` INSTEAD.
|
||||
|
||||
:return: none
|
||||
:rtype: NoReturn
|
||||
"""
|
||||
msg = "Do not use `with` for asyncio locks, use `async with` instead."
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc_value: BaseException | None,
|
||||
traceback: object,
|
||||
) -> None:
|
||||
"""Sync context manager exit is not supported because lock release is a coroutine."""
|
||||
msg = "Use `async with` — acquire/release are coroutines and cannot be awaited in a sync context manager."
|
||||
raise NotImplementedError(msg)
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
"""
|
||||
Acquire the lock.
|
||||
|
||||
:return: the lock object
|
||||
:returns: the lock object
|
||||
|
||||
"""
|
||||
await self.acquire()
|
||||
|
|
@ -314,9 +371,15 @@ class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
|
|||
await self.release()
|
||||
|
||||
def __del__(self) -> None:
|
||||
"""Called when the lock object is deleted."""
|
||||
with contextlib.suppress(RuntimeError):
|
||||
loop = self.loop or asyncio.get_running_loop()
|
||||
"""Release on deletion — safe to call during GC even when no event loop is running."""
|
||||
with contextlib.suppress(Exception):
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
# No running loop — try stored loop or create one
|
||||
loop = self._context.loop if self._context.loop and not self._context.loop.is_closed() else None
|
||||
if loop is None:
|
||||
return
|
||||
if not loop.is_running(): # pragma: no cover
|
||||
loop.run_until_complete(self.release(force=True))
|
||||
else:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue