|
| 1 | +# ============================================================================= |
| 2 | +# MIT License |
| 3 | +# Copyright (c) 2024 RocketRide Inc. |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in |
| 13 | +# all copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +# SOFTWARE. |
| 22 | +# ============================================================================= |
| 23 | + |
| 24 | +""" |
| 25 | +Token-bucket rate limiter with concurrency control for HTTP requests. |
| 26 | +
|
| 27 | +Enforces three independent limits: |
| 28 | + - requests per second (token bucket, refills every second) |
| 29 | + - requests per minute (token bucket, refills every minute) |
| 30 | + - max concurrent requests (semaphore) |
| 31 | +
|
| 32 | +All limits are configurable via services.json; sensible defaults are provided. |
| 33 | +Thread-safe: uses a single ``threading.Lock`` for the token buckets and a |
| 34 | +``threading.Semaphore`` for concurrency. |
| 35 | +""" |
| 36 | + |
| 37 | +from __future__ import annotations |
| 38 | + |
| 39 | +import threading |
| 40 | +import time |
| 41 | + |
| 42 | + |
| 43 | +class RateLimitError(Exception): |
| 44 | + """Raised when a request is rejected due to rate limiting.""" |
| 45 | + |
| 46 | + |
| 47 | +# Defaults used when services.json omits the fields. |
| 48 | +DEFAULT_MAX_PER_SECOND = 10 |
| 49 | +DEFAULT_MAX_PER_MINUTE = 100 |
| 50 | +DEFAULT_MAX_CONCURRENT = 5 |
| 51 | + |
| 52 | + |
| 53 | +class RateLimiter: |
| 54 | + """Token-bucket rate limiter with concurrent-request semaphore.""" |
| 55 | + |
| 56 | + def __init__( |
| 57 | + self, |
| 58 | + *, |
| 59 | + max_per_second: int = DEFAULT_MAX_PER_SECOND, |
| 60 | + max_per_minute: int = DEFAULT_MAX_PER_MINUTE, |
| 61 | + max_concurrent: int = DEFAULT_MAX_CONCURRENT, |
| 62 | + ) -> None: |
| 63 | + """Initialise token buckets and concurrency semaphore.""" |
| 64 | + # --- per-second bucket --- |
| 65 | + self._ps_capacity = max(max_per_second, 1) |
| 66 | + self._ps_tokens = float(self._ps_capacity) |
| 67 | + self._ps_refill_rate = float(self._ps_capacity) # tokens / second |
| 68 | + |
| 69 | + # --- per-minute bucket --- |
| 70 | + self._pm_capacity = max(max_per_minute, 1) |
| 71 | + self._pm_tokens = float(self._pm_capacity) |
| 72 | + self._pm_refill_rate = self._pm_capacity / 60.0 # tokens / second |
| 73 | + |
| 74 | + self._last_refill = time.monotonic() |
| 75 | + self._lock = threading.Lock() |
| 76 | + |
| 77 | + # --- concurrency semaphore --- |
| 78 | + self._max_concurrent = max(max_concurrent, 1) |
| 79 | + self._semaphore = threading.Semaphore(self._max_concurrent) |
| 80 | + |
| 81 | + # ------------------------------------------------------------------ |
| 82 | + # Public API |
| 83 | + # ------------------------------------------------------------------ |
| 84 | + |
| 85 | + def acquire(self) -> None: |
| 86 | + """Acquire a rate-limit slot, or raise ``RateLimitError``.""" |
| 87 | + # 1. Check concurrency limit first (non-blocking) so we never |
| 88 | + # consume tokens for a request that would be rejected anyway. |
| 89 | + if not self._semaphore.acquire(blocking=False): |
| 90 | + raise RateLimitError(f'Too many concurrent requests: max {self._max_concurrent} in-flight. Please wait for an ongoing request to complete.') |
| 91 | + |
| 92 | + # 2. Check token buckets (per-second + per-minute). |
| 93 | + try: |
| 94 | + with self._lock: |
| 95 | + self._refill() |
| 96 | + if self._ps_tokens < 1.0: |
| 97 | + raise RateLimitError(f'Rate limit exceeded: max {self._ps_capacity} requests per second. Please retry after a short delay.') |
| 98 | + if self._pm_tokens < 1.0: |
| 99 | + raise RateLimitError(f'Rate limit exceeded: max {self._pm_capacity} requests per minute. Please retry after a short delay.') |
| 100 | + self._ps_tokens -= 1.0 |
| 101 | + self._pm_tokens -= 1.0 |
| 102 | + except RateLimitError: |
| 103 | + self._semaphore.release() |
| 104 | + raise |
| 105 | + |
| 106 | + def release(self) -> None: |
| 107 | + """Release the concurrency slot after a request completes.""" |
| 108 | + self._semaphore.release() |
| 109 | + |
| 110 | + # ------------------------------------------------------------------ |
| 111 | + # Internals |
| 112 | + # ------------------------------------------------------------------ |
| 113 | + |
| 114 | + def _refill(self) -> None: |
| 115 | + """Refill both token buckets based on elapsed time. Caller holds ``_lock``.""" |
| 116 | + now = time.monotonic() |
| 117 | + elapsed = now - self._last_refill |
| 118 | + self._last_refill = now |
| 119 | + |
| 120 | + self._ps_tokens = min(self._ps_capacity, self._ps_tokens + elapsed * self._ps_refill_rate) |
| 121 | + self._pm_tokens = min(self._pm_capacity, self._pm_tokens + elapsed * self._pm_refill_rate) |
0 commit comments