[docs]classBucket(ABC):"""Abstract base class for buckets."""
[docs]asyncdef__aenter__(self)->Self:"""Enter the bucket context. It may for example start scheduling replenishments. """returnself
[docs]asyncdef__aexit__(self,*_:Any)->Optional[bool]:"""Exit the bucket context. It may for example cancel internal background tasks. """
[docs]@abstractmethodasyncdefwait_for_refill(self)->None:"""Wait until some tokens are replenished."""
[docs]@abstractmethoddefcan_acquire(self,tokens:float)->bool:"""Whether the given amount of tokens can be acquired. Args: tokens: The amount of tokens that we want to acquire. Returns: Whether the given amount of tokens is available to consume. """
[docs]@abstractmethoddefacquire(self,tokens:float)->None:"""Acquire the given amount of tokens. Args: tokens: The amount of tokens to acquire. Raises: RateLimit: Cannot acquire the given amount of tokens. """
def_assert_can_acquire(self,tokens:float)->None:"""Make sure that the given amount of tokens can be acquired. Args: tokens: The amount of tokens to acquire. Raises: RateLimit: Cannot acquire the given amount of tokens. """ifnotself.can_acquire(tokens):raiseRateLimit(f'Cannot acquire {tokens} tokens.')