Skip to content

rate_limiter_middleware

from pulsefire.middlewares import rate_limiter_middleware

Rate limiter middleware.

Should be positioned as late as possible in the client middlewares list.

Example:

rate_limiter = RiotAPIRateLimiter()
rate_limiter_middleware(rate_limiter)

Parameters:

Name Type Description Default
rate_limiter BaseRateLimiter

Rate limiter instance.

required
Source code in pulsefire/middlewares.py
def rate_limiter_middleware(rate_limiter: BaseRateLimiter):
    """Rate limiter middleware.

    Should be positioned as late as possible in the client middlewares list.

    Example:
    ```python
    rate_limiter = RiotAPIRateLimiter()
    rate_limiter_middleware(rate_limiter)
    ```

    Parameters:
        rate_limiter: Rate limiter instance.
    """

    track_429s = collections.deque(maxlen=12)

    def constructor(next: MiddlewareCallable):

        async def middleware(invocation: Invocation):
            while True:
                wait_for = await rate_limiter.acquire(invocation)
                if wait_for <= 0:
                    break
                await asyncio.sleep(wait_for)

            response: aiohttp.ClientResponse = await next(invocation)

            if response.status == 429:
                response_time = time.time()
                track_429s.append(response_time)
                if sum(response_time - prev_time < 10 for prev_time in track_429s) >= 10:
                    LOGGER.warning(f"rate_limiter_middleware: detected elevated amount of http 429 responses")
                    track_429s.clear()

            if wait_for == -1:
                await rate_limiter.synchronize(invocation, response.headers)

            return response

        return middleware

    return constructor