o
    wvXjå	  ã                   @   sD   d Z ddlmZmZ ddlmZ ddlmZ dZG dd„ de	ƒZ
dS )	z.Token bucket implementation for rate limiting.é    )Úabsolute_importÚunicode_literals)Údeque)Ú	monotonic)ÚTokenBucketc                   @   sZ   e Zd ZdZdZdZdZddd„Zdd„ Zdd	„ Z	d
d„ Z
ddd„Zddd„Zdd„ ZdS )r   a¨  Token Bucket Algorithm.

    See Also:
        https://en.wikipedia.org/wiki/Token_Bucket

        Most of this code was stolen from an entry in the ASPN Python Cookbook:
        https://code.activestate.com/recipes/511490/

    Warning:
        Thread Safety: This implementation is not thread safe.
        Access to a `TokenBucket` instance should occur within the critical
        section of any multithreaded code.
    Né   c                 C   s.   t |ƒ| _|| _t |ƒ| _tƒ | _tƒ | _d S ©N)ÚfloatÚcapacityÚ_tokensÚ	fill_rater   Ú	timestampr   Úcontents)Úselfr   r
   © r   úO/var/www/html/myproject/venv/lib/python3.10/site-packages/kombu/utils/limits.pyÚ__init__#   s
   

zTokenBucket.__init__c                 C   s   | j  |¡ d S r   )r   Úappend)r   Úitemr   r   r   Úadd*   s   zTokenBucket.addc                 C   s
   | j  ¡ S r   )r   Úpopleft©r   r   r   r   Úpop-   s   
zTokenBucket.popc                 C   s   | j  ¡  d S r   )r   Úclearr   r   r   r   Úclear_pending0   s   zTokenBucket.clear_pendingc                 C   s"   ||   ¡ kr|  j|8  _dS dS )aÆ  Check if one or more tokens can be consumed.

        Returns:
            bool: true if the number of tokens can be consumed
                from the bucket.  If they can be consumed, a call will also
                consume the requested number of tokens from the bucket.
                Calls will only consume `tokens` (the number requested)
                or zero tokens -- it will never consume a partial number
                of tokens.
        TF)Ú_get_tokensr   )r   Útokensr   r   r   Úcan_consume3   s   zTokenBucket.can_consumec                 C   s    |   ¡ }t||ƒ}|| | j S )zoReturn estimated time of token availability.

        Returns:
            float: the time in seconds.
        )r   Úmaxr   )r   r   r   r   r   r   Úexpected_timeC   s   
zTokenBucket.expected_timec                 C   sB   | j | jk rtƒ }| j|| j  }t| j| j | ƒ| _ || _| j S r   )r   r
   r   r   r   Úmin)r   ÚnowÚdeltar   r   r   r   M   s   zTokenBucket._get_tokens)r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r
   r   r   r   r   r   r   r   r   r   r   r   r   r      s    



r   N)r&   Ú
__future__r   r   Úcollectionsr   Ú
kombu.fiver   Ú__all__Úobjectr   r   r   r   r   Ú<module>   s    