|
| 1 | +"""Client-side rate-limiting middleware for aiohttp. |
| 2 | +
|
| 3 | +This middleware throttles outgoing requests using a token-bucket algorithm. |
| 4 | +It is *not* server-side rate limiting -- it limits how fast the client sends |
| 5 | +requests so it does not overwhelm upstream servers or exceed API quotas. |
| 6 | +
|
| 7 | +Features: |
| 8 | +- Configurable rate and burst size |
| 9 | +- Optional per-domain buckets |
| 10 | +- Automatic ``Retry-After`` header handling |
| 11 | +""" |
| 12 | + |
| 13 | +import asyncio |
| 14 | +import logging |
| 15 | +import time |
| 16 | +from collections import defaultdict, deque |
| 17 | +from http import HTTPStatus |
| 18 | + |
| 19 | +from aiohttp import ClientHandlerType, ClientRequest, ClientResponse |
| 20 | + |
| 21 | +_LOGGER = logging.getLogger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +class TokenBucket: |
| 25 | + """FIFO token-bucket using an ``asyncio.Event`` queue. |
| 26 | +
|
| 27 | + Each caller appends its own event to a FIFO queue and waits. A single |
| 28 | + ``_schedule`` coroutine services the queue front-to-back, sleeping until |
| 29 | + each slot's send time arrives and then unblocking the corresponding |
| 30 | + caller. This guarantees strict FIFO ordering even under high concurrency. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self, rate: float, burst: int) -> None: |
| 34 | + self._interval = 1.0 / rate |
| 35 | + self._burst = burst |
| 36 | + # Start *burst* intervals in the past so the first ``burst`` acquires |
| 37 | + # are instant. |
| 38 | + self._next_send = time.monotonic() - burst * self._interval |
| 39 | + self._waiters: deque[asyncio.Event] = deque() |
| 40 | + self._scheduling = False |
| 41 | + # Keep a strong reference to the scheduler task: the event loop only |
| 42 | + # holds a weak reference to it, so an otherwise-unreferenced task can |
| 43 | + # be garbage collected mid-run. |
| 44 | + self._scheduler_task: asyncio.Task[None] | None = None |
| 45 | + |
| 46 | + async def acquire(self) -> None: |
| 47 | + """Reserve the next send slot and wait until it arrives.""" |
| 48 | + event = asyncio.Event() |
| 49 | + self._waiters.append(event) |
| 50 | + self._ensure_scheduling() |
| 51 | + await event.wait() |
| 52 | + |
| 53 | + def _ensure_scheduling(self) -> None: |
| 54 | + """Start the scheduler loop if it is not already running.""" |
| 55 | + if not self._scheduling: |
| 56 | + self._scheduling = True |
| 57 | + self._scheduler_task = asyncio.ensure_future(self._schedule()) |
| 58 | + |
| 59 | + async def _schedule(self) -> None: |
| 60 | + """Service waiters in FIFO order, one slot at a time.""" |
| 61 | + while self._waiters: |
| 62 | + now = time.monotonic() |
| 63 | + # Cap drift so idle periods never accumulate more than *burst* |
| 64 | + # free slots. |
| 65 | + self._next_send = max(self._next_send, now - self._burst * self._interval) |
| 66 | + self._next_send += self._interval |
| 67 | + delay = self._next_send - now |
| 68 | + if delay > 0: |
| 69 | + await asyncio.sleep(delay) |
| 70 | + self._waiters.popleft().set() |
| 71 | + self._scheduling = False |
| 72 | + |
| 73 | + |
| 74 | +class RateLimitMiddleware: |
| 75 | + """Client middleware that throttles requests with a token bucket. |
| 76 | +
|
| 77 | + The middleware delays each outgoing request until the bucket grants it a |
| 78 | + slot, so the client never sends faster than ``rate`` requests per second |
| 79 | + (allowing short bursts of up to ``burst`` requests). |
| 80 | +
|
| 81 | + :param float rate: Sustained request rate, in requests per second. |
| 82 | + :param int burst: Number of requests allowed to go out back-to-back before |
| 83 | + throttling kicks in. |
| 84 | + :param bool per_domain: When ``True``, keep an independent bucket per |
| 85 | + target host instead of a single global bucket. |
| 86 | + :param bool respect_retry_after: When ``True``, sleep for the duration of a |
| 87 | + numeric ``Retry-After`` header on an HTTP 429 response before returning |
| 88 | + it to the caller. |
| 89 | + """ |
| 90 | + |
| 91 | + rate: float |
| 92 | + burst: int |
| 93 | + per_domain: bool |
| 94 | + respect_retry_after: bool |
| 95 | + |
| 96 | + def __init__( |
| 97 | + self, |
| 98 | + rate: float = 10.0, |
| 99 | + burst: int = 10, |
| 100 | + per_domain: bool = False, |
| 101 | + respect_retry_after: bool = True, |
| 102 | + ) -> None: |
| 103 | + self.rate = rate |
| 104 | + self.burst = burst |
| 105 | + self.per_domain = per_domain |
| 106 | + self.respect_retry_after = respect_retry_after |
| 107 | + self._global_bucket = TokenBucket(rate, burst) |
| 108 | + self._domain_buckets: dict[str, TokenBucket] = defaultdict( |
| 109 | + lambda: TokenBucket(rate, burst) |
| 110 | + ) |
| 111 | + |
| 112 | + def _get_bucket(self, request: ClientRequest) -> TokenBucket: |
| 113 | + if self.per_domain: |
| 114 | + domain = request.url.host or "unknown" |
| 115 | + return self._domain_buckets[domain] |
| 116 | + return self._global_bucket |
| 117 | + |
| 118 | + async def _handle_retry_after(self, response: ClientResponse) -> None: |
| 119 | + if response.status != HTTPStatus.TOO_MANY_REQUESTS: |
| 120 | + return |
| 121 | + retry_after = response.headers.get("Retry-After") |
| 122 | + if retry_after: |
| 123 | + try: |
| 124 | + wait_seconds = float(retry_after) |
| 125 | + _LOGGER.info("Server requested Retry-After: %ss", wait_seconds) |
| 126 | + await asyncio.sleep(wait_seconds) |
| 127 | + except ValueError: |
| 128 | + _LOGGER.debug( |
| 129 | + "Retry-After is not a number (likely HTTP-date): %s", retry_after |
| 130 | + ) |
| 131 | + |
| 132 | + async def __call__( |
| 133 | + self, |
| 134 | + request: ClientRequest, |
| 135 | + handler: ClientHandlerType, |
| 136 | + ) -> ClientResponse: |
| 137 | + """Run the request through the rate limiter.""" |
| 138 | + bucket = self._get_bucket(request) |
| 139 | + await bucket.acquire() |
| 140 | + |
| 141 | + response = await handler(request) |
| 142 | + |
| 143 | + if self.respect_retry_after: |
| 144 | + await self._handle_retry_after(response) |
| 145 | + |
| 146 | + return response |
0 commit comments