"""
Provide utilities for concurrent programming.
"""
import asyncio
import threading
import time
from abc import ABC, abstractmethod
from asyncio import sleep
from collections import defaultdict
from collections.abc import Hashable
from types import TracebackType
from typing import Self, final, MutableMapping
from math import floor
from typing_extensions import override
from betty.typing import threadsafe
[docs]
async def asynchronize_acquire(lock: threading.Lock, *, wait: bool = True) -> bool:
"""
Acquire a synchronous lock asynchronously.
"""
while not lock.acquire(blocking=False):
if not wait:
return False
# Sleeping for zero seconds does not actually sleep, but gives the event
# loop a chance to progress other tasks while we wait for another chance
# to acquire the lock.
await sleep(0)
return True
[docs]
@final
class AsynchronizedLock(Lock):
"""
Make a sychronous (blocking) lock asynchronous (non-blocking).
"""
__slots__ = "_lock"
[docs]
@classmethod
def threading(cls) -> Self:
"""
Create a new thread-safe, asynchronous lock.
"""
return cls(threading.Lock())
[docs]
@final
@threadsafe
class RateLimiter:
"""
Rate-limit operations.
This class implements the `Token Bucket algorithm <https://en.wikipedia.org/wiki/Token_bucket>`_.
"""
_PERIOD = 1
[docs]
def __init__(self, maximum: int):
self._lock = AsynchronizedLock.threading()
self._maximum = maximum
self._available: int | float = maximum
# A Token Bucket fills as time passes. However, we want callers to be able to start
# using the limiter immediately, so we 'preload' the first's period's tokens, and
# set the last added time to the end of the first period. This ensures there is no
# needless waiting if the number of tokens consumed in total is less than the limit
# per period.
self._last_add = time.monotonic() + self._PERIOD
[docs]
async def wait(self) -> None:
"""
Wait until an operation may be performed (again).
"""
async with self._lock:
while self._available < 1:
self._add_tokens()
if self._available < 1:
await asyncio.sleep(0)
self._available -= 1
[docs]
def ledger(self, transaction_id: Hashable) -> Lock:
"""
Ledger a new lock for the given transaction ID.
"""
return _Transaction(transaction_id, self._ledger_lock, self._ledger)