U
    ^g                     @  s  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZ ddlmZmZ ddlmZ ddlmZmZ ddlZddlZddlmZ dd	lmZmZmZ dd
lmZmZ ddl m!Z! ddl"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddlm0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@mAZA ejBG dd dZCG dd dZDG dd dZEdS )z
Flask-Limiter Extension
    )annotationsN)defaultdict)partialwraps)TracebackType)Typeoverload)ConfigurationError)MemoryStorageStoragestorage_from_string)
STRATEGIESRateLimiter)
OrderedSet)	http_date
parse_date   )request_context)MAX_BACKEND_CHECKS
ConfigVarsExemptionScopeHeaderNames)RateLimitExceeded)LimitManager)CallableDictListOptionalPRSequenceSetTupleTypeVarUnioncast)get_qualified_name)Limit
LimitGroupRequestLimitc                   @  sd   e Zd ZU dZded< ejedZded< eje	dZ
ded< ejedZd	ed
< ddddZdS )LimiterContextNOptional[RequestLimit]view_rate_limit)default_factoryList[RequestLimit]view_rate_limitszDict[Limit, List[str]]conditional_deductionszOrderedSet[Limit]seen_limitsNonereturnc                 C  s(   d | _ | j  | j  | j  d S N)r,   r/   clearr0   r1   self r9   ;/tmp/pip-unpacked-wheel-8ut481ky/flask_limiter/extension.pyreset;   s    

zLimiterContext.reset)__name__
__module____qualname__r,   __annotations__dataclassesfieldlistr/   dictr0   r   r1   r;   r9   r9   r9   r:   r*   2   s   
r*   c                    @  s  e Zd ZdZddddddddddddddddddddddddddddddddd	d
dddd	d
ddd	dddddd	d	ddddd	ddddddddZdddddZedddd Zdd!ddddddd"dd#
d$d%dddd
dddd&d'd(d)d*d+Zdd!ddddddd"d,	d$d-d%dddd
dddd&d(d.d/d0Z	e
ejejB ejB d1d2d3d2d4d5d6Ze
ejejB ejB d1d7d3d7d4d8d6Ze
ejejB ejB d1d3d9d:d;d6ZdqejejB ejB d1d<d3d=d4d>d6Zd?d?d@dAdBZddddCdDdEZdddFdGZdddHdIZdddJdKZedLddMdNZedOddPdQZedRddSdTZedUddVdWZdddXdYZdZdd[d\d]ZdZdZd[d^d_Zddd`dadbZdrdddddcdddedfZddcddgdhdiZdsddddjdkdlZdtdmddndodpZ dS )uLimitera  
    The :class:`Limiter` class initializes the Flask-Limiter extension.

    :param key_func: a callable that returns the domain to rate limit
      by.
    :param app: :class:`flask.Flask` instance to initialize the extension with.
    :param default_limits: a variable list of strings or callables
     returning strings denoting default limits to apply to all routes that are
     not explicitely decorated with a limit. :ref:`ratelimit-string` for  more details.
    :param default_limits_per_method: whether default limits are applied
     per method, per route or as a combination of all method per route.
    :param default_limits_exempt_when: a function that should return
     True/False to decide if the default limits should be skipped
    :param default_limits_deduct_when: a function that receives the
     current :class:`flask.Response` object and returns True/False to decide
     if a deduction should be made from the default rate limit(s)
    :param default_limits_cost: The cost of a hit to the default limits as an
     integer or a function that takes no parameters and returns an integer
     (Default: ``1``).
    :param application_limits: a variable list of strings or callables
     returning strings for limits that are applied to the entire application
     (i.e a shared limit for all routes)
    :param application_limits_per_method: whether application limits are applied
     per method, per route or as a combination of all method per route.
    :param application_limits_exempt_when: a function that should return
     True/False to decide if the application limits should be skipped
    :param application_limits_deduct_when: a function that receives the
     current :class:`flask.Response` object and returns True/False to decide
     if a deduction should be made from the application rate limit(s)
    :param application_limits_cost: The cost of a hit to the global application
     limits as an integer or a function that takes no parameters and returns an
     integer (Default: ``1``).
    :param headers_enabled: whether ``X-RateLimit`` response headers are
     written.
    :param header_name_mapping: Mapping of header names to use if
     :paramref:`Limiter.headers_enabled` is ``True``. If no mapping is provided
     the default values will be used.
    :param strategy: the strategy to use. Refer to :ref:`ratelimit-strategy`
    :param storage_uri: the storage location.
     Refer to :data:`RATELIMIT_STORAGE_URI`
    :param storage_options: kwargs to pass to the storage implementation
     upon instantiation.
    :param auto_check: whether to automatically check the rate limit in
     the before_request chain of the application. default ``True``
    :param swallow_errors: whether to swallow any errors when hitting a rate
     limit. An exception will still be logged. default ``False``
    :param fail_on_first_breach: whether to stop processing remaining limits
     after the first breach. default ``True``
    :param on_breach: a function that will be called when any limit in this
     extension is breached. If the function returns an instance of :class:`flask.Response`
     that will be the response embedded into the :exc:`RateLimitExceeded` exception
     raised.
    :param meta_limits: a variable list of strings or callables
     returning strings for limits that are used to control the upper limit of
     a requesting client hitting any configured rate limit. Once a meta limit is
     exceeded all subsequent requests will raise a :class:`~flask_limiter.RateLimitExceeded`
     for the duration of the meta limit window.
    :param on_meta_breach: a function that will be called when a meta limit in this
     extension is breached. If the function returns an instance of :class:`flask.Response`
     that will be the response embedded into the :exc:`RateLimitExceeded` exception
     raised.
    :param in_memory_fallback: a variable list of strings or callables
     returning strings denoting fallback limits to apply when the storage is
     down.
    :param in_memory_fallback_enabled: fall back to in memory
     storage when the main storage is down and inherits the original limits.
     default ``False``
    :param retry_after: Allows configuration of how the value of the
     `Retry-After` header is rendered. One of `http-date` or `delta-seconds`.
    :param key_prefix: prefix prepended to rate limiter keys and app context global names.
    :param request_identifier: a callable that returns the unique identity the current request.
     Defaults to :attr:`flask.Request.endpoint`
    :param enabled: Whether the extension is enabled or not
    NT )appdefault_limitsdefault_limits_per_methoddefault_limits_exempt_whendefault_limits_deduct_whendefault_limits_costapplication_limitsapplication_limits_per_methodapplication_limits_exempt_whenapplication_limits_deduct_whenapplication_limits_costheaders_enabledheader_name_mappingstrategystorage_uristorage_options
auto_checkswallow_errorsfail_on_first_breach	on_breachmeta_limitson_meta_breachin_memory_fallbackin_memory_fallback_enabledretry_after
key_prefixrequest_identifierenabledzCallable[[], str]zOptional[flask.Flask]z-Optional[List[Union[str, Callable[[], str]]]]zOptional[bool]Optional[Callable[[], bool]]3Optional[Callable[[flask.wrappers.Response], bool]]z'Optional[Union[int, Callable[[], int]]]z Optional[Dict[HeaderNames, str]]Optional[str]z$Optional[Dict[str, Union[str, int]]]boolEOptional[Callable[[RequestLimit], Optional[flask.wrappers.Response]]]zOptional[List[str]]strzOptional[Callable[..., str]]r2   )key_funcrF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   r4   c          !        s  | _ td _| _d _| _| _| _| _	|	 _
|
 _| _| _g  _|pf|oft|dk _i  _i  _g  _| _|pi  _| _| _| _|pi  _| _| _| _| _| _| _| _ | _!|r fdd|D ng }|r
 fdd|D ng }|r& fdd|D ng  _"|rT|D ]}  j#t$|  jd q6d  _%d  _&d _'d  _(d _)t**  _+t,  _- j.t/  t0||i i  j jd	 _1|r 2| d S )
Nzflask-limiterFr   c                   s   g | ]}t | jd qS )limit_providerkey_functionr(   	_key_func.0limitr7   r9   r:   
<listcomp>   s
   z$Limiter.__init__.<locals>.<listcomp>c                   s   g | ]}t | jd ddqS )globalTrj   rk   scopesharedrl   rn   r7   r9   r:   rq      s   c                   s   g | ]}t | jd ddqS )metaTrs   rl   rn   r7   r9   r:   rq      s   ri   )rL   rG   Zdecorated_limitsZblueprint_limitsZroute_exemptionsZblueprint_exemptions)3rF   logging	getLoggerloggerra   initialized_default_limits_per_method_default_limits_exempt_when_default_limits_deduct_when_default_limits_cost_application_limits_per_method_application_limits_exempt_when_application_limits_deduct_when_application_limits_cost_in_memory_fallbacklen_in_memory_fallback_enabledZ_route_exemptionsZ_blueprint_exemptions_request_filters_headers_enabled_header_mapping_retry_after	_strategy_storage_uri_storage_options_auto_check_swallow_errors_fail_on_first_breach
_on_breach_on_meta_breachrm   _key_prefix_request_identifier_meta_limitsappendr(   _storage_limiter_storage_dead_fallback_limiter_Limiter__check_backend_counttime_Limiter__last_check_backendset_marked_for_limiting
addHandlerNullHandlerr   limit_managerinit_app)!r8   rh   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   _default_limits_application_limitsrp   r9   r7   r:   __init__   s    )





	zLimiter.__init__zflask.Flask)rF   r4   c           	      C  s  |j }|tj| j| _| js"dS | jdkr@t|tjd| _| j	pP|tj
| _	| jpd|tj| _| jpz|tjd| _| jdkrt|tjd| _| jdkrt|tjd| _| jdkrt|tjd| _| j|tji  |tjd}|s| jstd d}ttt| jp(|f| j| _| j pJ|tj!d| _ | j t"krht#d| j  t"| j  | j| _$t%j&| j't%j&|tj(t%j&j)t%j*| j't%j*|tj+t%j*j)t%j,| j't%j,|tj-t%j,j)t%j.| j't%j.|tj/t%j.j)i| _'| j0p|tj1| _0| j2p*|tj3d	| _2| j4pF|tj5d
d | _4|tj6d}| j7pl|tj8d| _7| j9dkrt|tj:d| _9| j;p|tj<| _;| j=p|tj>| _=| j?j@s|r| j?AtB|| jCdd| j9| j;| j=| j7dg n@| j?j@}|D ]&}| j7|_D| j9|_E| j;|_F| j=|_Gq| j?A| |tjHd}| j?jIs|r| j?JtB|| jC| j| j	| j| jdg n@| j?jI}|D ]&}| j|_E| j	|_F| j|_G| j|_Dq| j?J| |tjKd}| jLs|rtB|| jCdddg| _L| jMp|tjNd| _M| jOp |tjPd| _O| Q|| j  | |jRdtS krz| jTr\|U| jV |WtXtYjZ|  |[| j\ |jRd ]|  d| _^dS )zJ
        :param app: :class:`flask.Flask` instance to rate limit.
        NFr   Ta	  Using the in-memory storage for tracking rate limits as no storage was explicitly specified. This is not recommended for production use. See: https://flask-limiter.readthedocs.io#configuring-a-storage-backend for documentation about configuring the storage backend.z	memory://zfixed-windowz!Invalid rate limiting strategy %srE   c                   S  s   t jjp
dS )NrE   )flaskrequestendpointr9   r9   r9   r:   <lambda>~      z"Limiter.init_app.<locals>.<lambda>rr   )rj   rk   rt   ru   
per_methodexempt_whendeduct_whencost)rj   rk   r   r   r   r   rv   rs   limiter)_config
setdefaultr   ZENABLEDra   r{   re   getZDEFAULT_LIMITS_PER_METHODr|   ZDEFAULT_LIMITS_EXEMPT_WHENr}   ZDEFAULT_LIMITS_DEDUCT_WHENr~   ZDEFAULT_LIMITS_COSTr   ZSWALLOW_ERRORSr   ZFAIL_ON_FIRST_BREACHr   ZHEADERS_ENABLEDr   updateZSTORAGE_OPTIONSZSTORAGE_URIr   warningswarnr%   r   r   r   r   ZSTRATEGYr   r	   r   r   RESETr   ZHEADER_RESETvalue	REMAININGZHEADER_REMAININGLIMITZHEADER_LIMITRETRY_AFTERZHEADER_RETRY_AFTERr   ZHEADER_RETRY_AFTER_VALUEr   Z
KEY_PREFIXr   ZREQUEST_IDENTIFIERZAPPLICATION_LIMITSr   ZAPPLICATION_LIMITS_COSTr   ZAPPLICATION_LIMITS_PER_METHODr   ZAPPLICATION_LIMITS_EXEMPT_WHENr   ZAPPLICATION_LIMITS_DEDUCT_WHENr   r   Zset_application_limitsr(   rm   r   r   r   r   ZDEFAULT_LIMITSr   Zset_default_limitsZMETA_LIMITSr   r   Z	ON_BREACHr   ZON_META_BREACH_Limiter__configure_fallbacks
extensionsr   r   Zbefore_request_check_request_limitZafter_requestr   rD   _Limiter__inject_headersZteardown_request_Limiter__release_contextaddrz   )	r8   rF   r   Zstorage_uri_from_configZ
app_limitsgroupZconf_limitsZdefault_limit_groupsrZ   r9   r9   r:   r   $  sB   



 



        

	 zLimiter.init_appr*   r3   c                 C  s2   t  }t|dstt|_ttttf |j|  S )aU  
        The context is meant to exist for the lifetime
        of a request/response cycle per instance of the extension
        so as to keep track of any state used at different steps
        in the lifecycle (for example to pass information
        from the before request hook to the after_request hook)

        :meta private:
        _limiter_request_context)r   hasattrr   r*   r   r%   r   rD   )r8   ctxr9   r9   r:   context  s    


zLimiter.contextFr   )
rh   r   methodserror_messager   override_defaultsr   rY   r   rt   zUnion[str, Callable[[], str]]Optional[Callable[[], str]]zUnion[int, Callable[[], int]]z*Optional[Union[str, Callable[[str], str]]]LimitDecorator)limit_valuerh   r   r   r   r   r   r   rY   r   rt   r4   c       
         C  s"   t | ||d||||||||	|
dS )av	  
        Decorator to be used for rate limiting individual routes or blueprints.

        :param limit_value: rate limit string or a callable that returns a
         string. :ref:`ratelimit-string` for more details.
        :param key_func: function/lambda to extract the unique
         identifier for the rate limit. defaults to remote address of the
         request.
        :param per_method: whether the limit is sub categorized into the
         http method of the request.
        :param methods: if specified, only the methods in this list will
         be rate limited (default: ``None``).
        :param error_message: string (or callable that returns one) to override
         the error message used in the response.
        :param exempt_when: function/lambda used to decide if the rate
         limit should skipped.
        :param override_defaults:  whether the decorated limit overrides
         the default limits (Default: ``True``).

         .. note:: When used with a :class:`~flask.Blueprint` the meaning
            of the parameter extends to any parents the blueprint instance is
            registered under. For more details see :ref:`recipes:nested blueprints`

        :param deduct_when: a function that receives the current
         :class:`flask.Response` object and returns True/False to decide if a
         deduction should be done from the rate limit
        :param on_breach: a function that will be called when this limit
         is breached. If the function returns an instance of :class:`flask.Response`
         that will be the response embedded into the :exc:`RateLimitExceeded` exception
         raised.
        :param cost: The cost of a hit or a function that
         takes no parameters and returns the cost as an integer (Default: ``1``).
        :param scope: a string or callable that returns a string
         for further categorizing the rate limiting scope. This scope is combined
         with the current endpoint of the request.


        Changes
          - .. versionadded:: 2.9.0 The returned object can also be used as a context manager
            for rate limiting a code block inside a view. For example::

                @app.route("/")
                def route():
                   try:
                       with limiter.limit("10/second"):
                           # something expensive
                   except RateLimitExceeded: pass
        Fr   r   r   r   r   r   rY   r   r   )r8   r   rh   r   r   r   r   r   r   rY   r   rt   r9   r9   r:   rp     s    BzLimiter.limit)	rh   r   r   r   r   r   r   rY   r   z Union[str, Callable[[str], str]])r   rt   rh   r   r   r   r   r   r   rY   r   r4   c       	         C  s"   t | ||d|||||||	|
|dS )a  
        decorator to be applied to multiple routes sharing the same rate limit.

        :param limit_value: rate limit string or a callable that returns a
         string. :ref:`ratelimit-string` for more details.
        :param scope: a string or callable that returns a string
         for defining the rate limiting scope.
        :param key_func: function/lambda to extract the unique
         identifier for the rate limit. defaults to remote address of the
         request.
        :param per_method: whether the limit is sub categorized into the
         http method of the request.
        :param methods: if specified, only the methods in this list will
         be rate limited (default: ``None``).
        :param error_message: string (or callable that returns one) to override
         the error message used in the response.
        :param function exempt_when: function/lambda used to decide if the rate
         limit should skipped.
        :param override_defaults: whether the decorated limit overrides
         the default limits. (default: ``True``)

         .. note:: When used with a :class:`~flask.Blueprint` the meaning
            of the parameter extends to any parents the blueprint instance is
            registered under. For more details see :ref:`recipes:nested blueprints`
        :param deduct_when: a function that receives the current
         :class:`flask.Response`  object and returns True/False to decide if a
         deduction should be done from the rate limit
        :param on_breach: a function that will be called when this limit
         is breached. If the function returns an instance of :class:`flask.Response`
         that will be the response embedded into the :exc:`RateLimitExceeded` exception
         raised.
        :param cost: The cost of a hit or a function that
         takes no parameters and returns the cost as an integer (default: ``1``).
        Tr   r   )r8   r   rt   rh   r   r   r   r   r   r   rY   r   r9   r9   r:   shared_limitA  s    4zLimiter.shared_limitflagsflask.Blueprintr   )objr   r4   c                C  s   d S r5   r9   r8   r   r   r9   r9   r:   exempt  s    zLimiter.exemptzCallable[..., R]c                C  s   d S r5   r9   r   r9   r9   r:   r     s    z_Union[Callable[[Callable[P, R]], Callable[P, R]], Callable[[flask.Blueprint], flask.Blueprint]])r   r4   c                C  s   d S r5   r9   )r8   r   r9   r9   r:   r     s    
z2Optional[Union[Callable[..., R], flask.Blueprint]]zUnion[Callable[..., R], flask.Blueprint, Callable[[Callable[P, R]], Callable[P, R]], Callable[[flask.Blueprint], flask.Blueprint]]c                  sr   t |tjrj|j  nP|r6jt|  n8td}tdt	d|f tj}ddd fdd}|S |S )a  
        Mark a view function or all views in a blueprint as exempt from
        rate limits.

        :param obj: view function or blueprint to mark as exempt.
        :param flags: Controls the scope of the exemption. By default
         application wide limits, defaults configured on the extension and meta limits
         are opted out of. Additional flags can be used to control the behavior
         when :paramref:`obj` is a Blueprint that is nested under another Blueprint
         or has other Blueprints nested under it (See :ref:`recipes:nested blueprints`)

        The method can be used either as a decorator without any arguments (the default
        flags will apply and the route will be exempt from default and application limits::

            @app.route("...")
            @limiter.exempt
            def route(...):
               ...

        Specific exemption flags can be provided at decoration time::

            @app.route("...")
            @limiter.exempt(flags=ExemptionScope.APPLICATION)
            def route(...):
                ...

        If an entire blueprint (i.e. all routes under it) are to be exempted the method
        can be called with the blueprint as the first parameter and any additional flags::

            bp = Blueprint(...)
            limiter.exempt(bp)
            limiter.exempt(
                bp,
                flags=ExemptionScope.DEFAULT|ExemptionScope.APPLICATION|ExemptionScope.ANCESTORS
            )

        _R_WO.r   r4   c                   s   j |  dS )Nr   )r   )r   r   r8   r9   r:   wrapper  s    zLimiter.exempt.<locals>.wrapper)

isinstancer   	Blueprintr   Zadd_blueprint_exemptionnameZadd_route_exemptionr&   r#   r   )r8   r   r   r   r   r   r9   r   r:   r     s    3zCallable[[], bool])fnr4   c                 C  s   | j | |S )a  
        decorator to mark a function as a filter to be executed
        to check if the request is exempt from rate limiting.

        :param fn: The function will be called before evaluating any rate limits
         to decide whether to perform rate limit or skip it.
        )r   r   )r8   r   r9   r9   r:   request_filter  s    zLimiter.request_filter)rF   rS   r4   c                 C  s   |j }|tjd}|tjd }| jsD|rDt|| jd dddg| _| js^|pZt	| jdk| _| jr|t
 | _t| | j| _d S )NFr   )rj   rk   rt   r   r   r   )r   r   r   ZIN_MEMORY_FALLBACK_ENABLEDZIN_MEMORY_FALLBACKr   r(   rm   r   r   r
   Z_fallback_storager   r   )r8   rF   rS   r   Zfallback_enabledfallback_limitsr9   r9   r:   Z__configure_fallbacks  s$    

zLimiter.__configure_fallbacksc                 C  sJ   | j tkrd| _ t | j td| j krFt | _|  j d7  _ dS dS )Nr      r   TF)r   r   r   r   powr7   r9   r9   r:   Z__should_check_backend  s    

zLimiter.__should_check_backendc                 C  s   | j dd dS )z
        Explicitly check the limits for the current request. This is only relevant
        if the extension was initialized with :paramref:`~flask_limiter.Limiter.auto_check`
        set to ``False``


        :raises: RateLimitExceeded
        F)in_middlewareN)r   r7   r9   r9   r:   check  s    	zLimiter.checkc                 C  s@   z| j   | jd W n  tk
r:   | jd Y nX dS )z?
        resets the storage if it supports being reset
        z-Storage has been reset and all limits clearedz.This storage type does not support being resetN)storager;   ry   infoNotImplementedErrorwarningr7   r9   r9   r:   r;   "  s
    
zLimiter.resetr   c                 C  s   | j s
t| j S )zE
        The backend storage configured for the rate limiter
        )r   AssertionErrorr7   r9   r9   r:   r   ,  s    
zLimiter.storager   c                 C  s&   | j r| jr| j}n| j}|s"t|S )zc
        Instance of the rate limiting strategy used for performing
        rate limiting.
        )r   r   r   r   r   )r8   r   r9   r9   r:   r   4  s
    zLimiter.limiterr+   c                 C  s   | j jS )aN  
        Get details for the most relevant rate limit used in this request.

        In a scenario where multiple rate limits are active for a single request
        and none are breached, the rate limit which applies to the smallest
        time window will be returned.

        .. important:: The value of ``remaining`` in :class:`RequestLimit` is after
           deduction for the current request.


        For example::

            @limit("1/second")
            @limit("60/minute")
            @limit("2/day")
            def route(...):
                ...

        - Request 1 at ``t=0`` (no breach): this will return the details for for ``1/second``
        - Request 2 at ``t=1`` (no breach): it will still return the details for ``1/second``
        - Request 3 at ``t=2`` (breach): it will return the details for ``2/day``
        )r   r,   r7   r9   r9   r:   current_limitA  s    zLimiter.current_limitr.   c                 C  s   | j jS )z
        Get a list of all rate limits that were applicable and evaluated
        within the context of this request.

        The limits are returned in a sorted order by smallest window size first.
        )r   r/   r7   r9   r9   r:   current_limits\  s    	zLimiter.current_limitsc                 C  s"   | j r| jr| jst|  S dS )a\  
        Returns the identity of the request (by default this is the
        :attr:`flask.Request.endpoint` associated by the view function
        that is handling the request). The behavior can be customized
        by initializing the extension with a callable argument for
        :paramref:`~flask_limiter.Limiter.request_identifier`.
        rE   )rz   ra   r   r   r7   r9   r9   r:   identify_requestg  s    
zLimiter.identify_requestzflask.wrappers.Response)responser4   c                 C  s   | j j D ]t\}}|jr||rz | jj|jf|d|ji W q tk
r~ } z| j	rj| j
d n|W 5 d }~X Y qX qd S )Nr   z-Failed to deduct rate limit. Swallowing error)r   r0   itemsr   r   hitrp   r   	Exceptionr   ry   	exception)r8   r   limargserrr9   r9   r:   Z__check_conditional_deductionst  s     z&Limiter.__check_conditional_deductionsc              
   C  s  |  | | j}| jr| jr|r| jrz|j}|j| jtj	 t
|jj |j| jtj t
|j |j| jtj t
| |jd}|d k	rt|}|d krt t| }t|tjrt| }tt||}|j| jtj t
| jdkrt|nt|t   W nl tk
r } zL| jrd| jsd| j !d d| _| "|}n| j#rz| j $d n|W 5 d }~X Y nX |S )NzRetry-Afterz	http-dateBRate limit storage unreachable - falling back to in-memory storageTz5Failed to update rate limit headers. Swallowing error)%&_Limiter__check_conditional_deductionsr   ra   r   r   reset_atheadersr   r   r   rg   rp   amountr   	remainingr   r   r   r   intr   datetimemktime	timetuplemaxr   r   r   r   r   r   r   ry   r   r   r   r   )r8   r   Zheader_limitr   Zexisting_retry_after_headerr^   er9   r9   r:   Z__inject_headers  sn    




 
zLimiter.__inject_headers)r   r4   c                 C  s>   t | p:| jo| j p:|dd dkp:tdd | jD S )N.Zstaticc                 s  s   | ]}| V  qd S r5   r9   )ro   r   r9   r9   r:   	<genexpr>  s     z4Limiter.__check_all_limits_exempt.<locals>.<genexpr>)re   ra   rz   splitanyr   )r8   r   r9   r9   r:   Z__check_all_limits_exempt  s    z!Limiter.__check_all_limits_exemptzList[Limit])r   	blueprintcallable_namer   r4   c                 C  s
  |r
|}n$t jj|pdd }|r*t|nd}| |r<g S || jkpT| j|pRd}g }| j	r| j
r|rv|| jkrvnB|  r| jr| j r| jd d| _	d| _nttj| j }|r|S | jt j|||||\}	}
t|	| jj }| jj|	 t|t|
 S )NrE   zRate limit storage recoveredFr   )r   current_appview_functionsr   r&   !_Limiter__check_all_limits_exemptr   r   Z	has_hintsr   r   _Limiter__should_check_backendr   r   ry   r   r   rB   	itertoolschainr   Zresolve_limitsr   r   r1   r   )r8   r   r  r  r   r   	view_funcZmarked_for_limitingr   defaultsZ	decoratedlimitsr9   r9   r:   Z__filter_limits  sH    

zLimiter.__filter_limits)r   r  r4   c                 C  s  g }d }g }t tj| j }tj| jtj	|tj
j@ s|D ]}| ||d  }}	||	g}
| jj|jf|
d|jis>t| |j|
d|j}|| j_|g| j_d }| jrz | |}t|tjjr|}W n> tk
r } z| jr| jd| n|W 5 d }~X Y nX t||dq>t |dd dD ]}|j!s,|j"rFq,||tj
j#}| }||g}
i }t$|
s| j%d|j d	 q,| j&r| j&f|
}
|j'r|
| jj(|< | jj}n| jj)}|j|d< t| |j|
d
|j}|*| ||jf|
|s,| j+d|j|| |*||
f d|d _,|d }| j-r, qJq,|sz|rzdd |D }|rr|d n|d }|pd | j_|| j_d }|D ]}t| |d j|d d|d j}t./| j0|d j1gD ]n}|rz ||}t|tjjr|}W n@ tk
r< } z | jr(| jd| n|W 5 d }~X Y nX qҐq|r|D ]:}||tj
j#}| }||g}
| jj)|jf|
  qPtt |dd dd d |dd S )Nr   Tz,on_meta_breach callback failed with error %s)r   c                 S  s   | j S r5   rp   xr9   r9   r:   r   )  r   z+Limiter.__evaluate_limits.<locals>.<lambda>)keyzSkipping limit: z". Empty value found in parameters.Fz*ratelimit %s (%s) exceeded at endpoint: %sr  c                 S  s   g | ]}|j s|qS r9   )ru   rn   r9   r9   r:   rq   W  s      z-Limiter.__evaluate_limits.<locals>.<listcomp>r   r   z'on_breach callback failed with error %sc                 S  s
   | d j S )Nr   r  r  r9   r9   r:   r   v  r   )2rB   r  r  r   r   METAr   Zexemption_scoper   r  r   r  rh   Z	scope_forr   testrp   r   r)   ru   r   r,   r/   r   r   wrappersResponser   r   ry   r   r   sortedZ	is_exemptZmethod_exemptmethodallerrorr   r   r0   r   r   r   Zbreachedr   rC   fromkeysr   rY   )r8   r   r  Zfailed_limitsZlimit_for_headerZview_limitsrZ   r   Z	limit_keyrt   r   Zbreached_meta_limitZmeta_breach_responseZcb_responser   Zlimit_scopekwargsr  Zrequest_limitexplicitZon_breach_responserp   cbr9   r9   r:   Z__evaluate_limits  s          

 





     zLimiter.__evaluate_limits)r  r   r4   c              
   C  s   |   }z$| |tjj||}| || W n tk
r } zdt|trL|| j	r| j
s| jd d| _
| jj  | j||d n| jr| jd n|W 5 d }~X Y nX d S )Nr   T)r  r   z&Failed to rate limit. Swallowing error)r   _Limiter__filter_limitsr   r   r  _Limiter__evaluate_limitsr   r   r   r   r   ry   r   r   r1   r6   r   r   r   )r8   r  r   r   Z
all_limitsr   r9   r9   r:   r   z  s2    
 zLimiter._check_request_limitOptional[BaseException])_r4   c                 C  s   | j   d S r5   )r   r;   )r8   r#  r9   r9   r:   Z__release_context  s    zLimiter.__release_context)N)F)NT)N)!r<   r=   r>   __doc__r   r   propertyr   rp   r   r   r   ZAPPLICATIONDEFAULTr  r   r   r   r
  r   r;   r   r   r   r   r   r   r   r	  r   r!  r   r   r9   r9   r9   r:   rD   B   s   OL  9(W(D		 A

G 3u    rD   c                   @  s   e Zd ZdZd*dddd	d
d	dddd	ddddddZeddddZddddZddddddd Ze	d!d!d"d#d$Z
e	d%dd"d&d$Z
d'd(d"d)d$Z
dS )+r   z
    Wrapper used by :meth:`~flask_limiter.Limiter.limit`
    and :meth:`~flask_limiter.Limiter.shared_limit`
    when wrapping view functions or blueprints.
    NFTr   rD   zUnion[Callable[[], str], str]r   re   z*Optional[Union[Callable[[str], str], str]]zOptional[Sequence[str]]rd   rb   rc   rf   zUnion[Callable[[], int], int])r   r   rh   ru   rt   r   r   r   r   r   r   rY   r   c                 C  sz   t || _|| _|p| jj| _|| _|| _|r8t|nd | _	|| _
|	| _|
| _|| _|| _|| _t| j | _|| _d S r5   )weakrefproxyr   r   rm   rh   rt   r   tupler   r   r   r   r   rY   r   callableZ	is_staticru   )r8   r   r   rh   ru   rt   r   r   r   r   r   r   rY   r   r9   r9   r:   r     s    zLimitDecorator.__init__r(   r3   c                 C  s8   t | j| j| j| j| j| j| j| j| j	| j
| j| jdS )N)rj   rk   rt   r   r   r   r   r   r   rY   r   ru   )r(   r   rh   rt   r   r   r   r   r   r   rY   r   ru   r7   r9   r9   r:   limit_group  s    zLimitDecorator.limit_groupr2   c                 C  sr   t jdd}|d j d|d j d|d j }| jjj|| jdd | jj	| j
 | | jjd|d d S )	Nr   r  r   :T)overrideFr   r  )	tracebackextract_stackfilenamer   linenor   r   add_decorated_limitr+  add_endpoint_hintr   r   )r8   tbZqualified_locationr9   r9   r:   	__enter__  s    &    zLimitDecorator.__enter__zOptional[Type[BaseException]]r"  zOptional[TracebackType])exc_type	exc_valuer/  r4   c                 C  s   d S r5   r9   )r8   r7  r8  r/  r9   r9   r:   __exit__  s    zLimitDecorator.__exit__zCallable[P, R]r   c                 C  s   d S r5   r9   r8   r   r9   r9   r:   __call__  s    zLimitDecorator.__call__r   c                 C  s   d S r5   r9   r:  r9   r9   r:   r;    s    z&Union[Callable[P, R], flask.Blueprint]zOptional[Callable[P, R]]c                   s   t tjrj nt t tjr>jj j d S jj	
  jj j tdddd fdd}t|dj |S d S )NzP.argszP.kwargsr   )akr4   c                    s   j jrhtdd j kshj  }|rXtjj|d }|rXt| ksXj j	
|  j jd d tttj| |S )N__wrapper-limiter-instanceFr.  )r   r   getattrr   r   r  r  r   r&   r   r4  r   r%   r   Zensure_sync)r<  r=  identityr  r   r   r8   r9   r:   Z__inner  s     

 z(LimitDecorator.__call__.<locals>.__innerr>  )r   r   r   r   r&   r   r   Zadd_blueprint_limitr+  r   r   r3  r   setattr)r8   r   Z_LimitDecorator__innerr9   rA  r:   r;    s    )NFNFNNNTNNr   )r<   r=   r>   r$  r   r%  r+  r6  r9  r   r;  r9   r9   r9   r:   r     s,   
           (!r   )Fr$  
__future__r   r@   r   r  rw   r   r/  r   r'  collectionsr   	functoolsr   r   typesr   typingr   r   r   Zflask.wrappersZlimits.errorsr	   Zlimits.storager
   r   r   Zlimits.strategiesr   r   Zordered_setr   Zwerkzeug.httpr   r   _compatr   	constantsr   r   r   r   errorsr   managerr   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   utilr&   r  r'   r(   r)   	dataclassr*   rD   r   r9   r9   r9   r:   <module>   sN   8        d