Coverage for src/taipanstack/utils/rate_limit.py: 100%

182 statements  

« prev     ^ index     » next       coverage.py v7.15.1, created at 2026-11-23 17:43 +0000

1""" 

2Rate limiting utilities. 

3 

4Provides an in-memory token-bucket based rate limiting decorator 

5for both synchronous and asynchronous functions. The decorator 

6returns a ``Result`` type encapsulating the original return value 

7or a ``RateLimitError`` error. 

8""" 

9 

10import contextlib 

11import functools 

12import inspect 

13import math 

14import threading 

15import time 

16from collections.abc import Awaitable, Callable 

17from typing import ParamSpec, Protocol, TypeVar, cast, overload 

18 

19from taipanstack.core.result import Err, Ok, Result 

20 

21__all__ = ["RateLimitError", "RateLimiter", "rate_limit"] 

22 

23P = ParamSpec("P") 

24T = TypeVar("T") 

25 

26 

27class RateLimitError(Exception): 

28 """Exception raised when a rate limit is exceeded.""" 

29 

30 def __init__(self, message: str = "Rate limit exceeded") -> None: 

31 """Initialize the RateLimitError. 

32 

33 Args: 

34 message: The error message to display.Defaults to "Rate limit exceeded". 

35 

36 """ 

37 super().__init__(message) 

38 

39 

40class RateLimiter: 

41 """Token bucket rate limiter logic.""" 

42 

43 def _is_finite_number(self, val: float | int) -> bool: 

44 return isinstance(val, (int, float)) and math.isfinite(val) 

45 

46 def _validate_finite(self, max_calls: int, time_window: float) -> None: 

47 """Check if parameters are finite numbers.""" 

48 if not self._is_finite_number(max_calls) or not self._is_finite_number( 

49 time_window 

50 ): 

51 raise ValueError("max_calls and time_window must be finite numbers") 

52 

53 def _validate_positive(self, max_calls: int, time_window: float) -> None: 

54 """Check if parameters are positive.""" 

55 if max_calls <= 0: 

56 raise ValueError("max_calls and time_window must be > 0.0") 

57 if time_window <= 0: 

58 raise ValueError("max_calls and time_window must be > 0.0") 

59 

60 def _validate_init_params(self, max_calls: int, time_window: float) -> None: 

61 """Validate initialization parameters.""" 

62 self._validate_finite(max_calls, time_window) 

63 self._validate_positive(max_calls, time_window) 

64 

65 def __init__(self, max_calls: int, time_window: float) -> None: 

66 """Initialize the token bucket. 

67 

68 Args: 

69 max_calls: The maximum number of calls allowed in the time window. 

70 time_window: The time window in seconds. 

71 

72 """ 

73 self._validate_init_params(max_calls, time_window) 

74 self.capacity: float = float(max_calls) 

75 self.time_window: float = float(time_window) 

76 self.tokens: float = self.capacity 

77 self.last_update: float = time.monotonic() 

78 self._lock = threading.Lock() 

79 

80 def _is_valid_time_window(self) -> bool: 

81 """Check if time window is valid.""" 

82 if not isinstance(self.time_window, (int, float)): 

83 return False # type: ignore[unreachable] 

84 return math.isfinite(self.time_window) and self.time_window > 0.0 

85 

86 def _is_valid_capacity(self) -> bool: 

87 """Check if capacity is valid.""" 

88 if not isinstance(self.capacity, (int, float)): 

89 return False # type: ignore[unreachable] 

90 return math.isfinite(self.capacity) and self.capacity > 0.0 

91 

92 def _is_valid_bucket_state(self) -> bool: 

93 """Check if the bucket's time window and capacity are in a valid state.""" 

94 return self._is_valid_time_window() and self._is_valid_capacity() 

95 

96 def _calculate_new_tokens(self, elapsed: float) -> float | None: 

97 """Calculate new tokens based on elapsed time.""" 

98 try: 

99 new_tokens = elapsed * (self.capacity / self.time_window) 

100 return new_tokens if math.isfinite(new_tokens) else None 

101 except Exception: 

102 return None 

103 

104 def _validate_token_types(self, new_tokens: float) -> bool: 

105 """Validate the types of tokens.""" 

106 if not isinstance(self.tokens, (int, float)): 

107 self.tokens = self.capacity # type: ignore[unreachable] 

108 return False 

109 return isinstance(new_tokens, (int, float)) 

110 

111 def _update_tokens_value(self, new_tokens: float) -> bool: 

112 """Update tokens value safely.""" 

113 try: 

114 self.tokens += new_tokens 

115 if not math.isfinite(self.tokens): 

116 self.tokens = self.capacity 

117 return False 

118 self.tokens = min(self.tokens, self.capacity) 

119 return True 

120 except Exception: 

121 self.tokens = self.capacity 

122 return False 

123 

124 def _apply_new_tokens(self, new_tokens: float) -> bool: 

125 """Apply new tokens to the bucket.""" 

126 if not self._validate_token_types(new_tokens): 

127 return False 

128 return self._update_tokens_value(new_tokens) 

129 

130 def _calculate_elapsed(self, now: float) -> float | None: 

131 """Calculate the elapsed time since the last update.""" 

132 if not isinstance(self.last_update, (int, float)): 

133 return None # type: ignore[unreachable] 

134 try: 

135 raw_elapsed = now - self.last_update 

136 if not math.isfinite(raw_elapsed): 

137 return None 

138 return max(0.0, raw_elapsed) 

139 except Exception: 

140 return None 

141 

142 def _calculate_tokens_to_add(self, elapsed: float) -> float | None: 

143 """Calculate new tokens based on elapsed time and valid state.""" 

144 # Prevent state corruption or infinite elapsed time 

145 if not self._is_valid_bucket_state(): 

146 return None 

147 

148 return self._calculate_new_tokens(elapsed) 

149 

150 def _add_tokens(self, now: float) -> bool: 

151 """Calculate and add new tokens to the bucket based on elapsed time. 

152 

153 Args: 

154 now: Current monotonic time. 

155 

156 Returns: 

157 True if token update succeeds, False if state corruption is detected. 

158 

159 """ 

160 elapsed = self._calculate_elapsed(now) 

161 if elapsed is None: 

162 return False 

163 

164 new_tokens = self._calculate_tokens_to_add(elapsed) 

165 if new_tokens is None: 

166 return False 

167 

168 # Always advance time even if apply fails, to prevent starvation 

169 apply_success = self._apply_new_tokens(new_tokens) 

170 self.last_update = now 

171 return apply_success 

172 

173 def _check_tokens_validity(self) -> bool: 

174 """Check tokens validity.""" 

175 if not isinstance(self.tokens, (int, float)): 

176 return False # type: ignore[unreachable] 

177 if not math.isfinite(self.tokens): 

178 self.tokens = self.capacity 

179 return False 

180 return True 

181 

182 def _try_consume(self, tokens: float) -> bool: 

183 """Attempt to consume the tokens from the bucket if available.""" 

184 try: 

185 if not self._check_tokens_validity(): 

186 return False 

187 if self.tokens >= tokens: 

188 self.tokens -= tokens 

189 return True 

190 return False 

191 except Exception: 

192 self.tokens = self.capacity 

193 return False 

194 

195 def _get_current_time(self) -> float | None: 

196 """Get current monotonic time safely.""" 

197 try: 

198 return time.monotonic() 

199 except Exception: 

200 return None 

201 

202 def _validate_and_add_tokens(self, now: float | None) -> bool: 

203 """Validate time and add tokens. 

204 

205 Returns True if tokens were added successfully, False otherwise. 

206 """ 

207 if now is None: 

208 return False 

209 if not isinstance(now, (int, float)): 

210 return False # type: ignore[unreachable] 

211 if not math.isfinite(now): 

212 # If not finite, we can't add tokens, but we shouldn't fail 

213 # the consumption if there are already tokens. 

214 return True 

215 return self._add_tokens(now) 

216 

217 def _process_consumption(self, tokens: float) -> bool: 

218 """Process token consumption inside the lock.""" 

219 now = self._get_current_time() 

220 

221 # Prevent time corruption from poisoning the bucket state. 

222 # Only try to add tokens if time is finite. 

223 if not self._validate_and_add_tokens(now): 

224 return False 

225 

226 return self._try_consume(tokens) 

227 

228 def _is_valid_token_amount(self, tokens: float) -> bool: 

229 """Check if requested token amount is valid.""" 

230 if not isinstance(tokens, (int, float)): 

231 return False # type: ignore[unreachable] 

232 return math.isfinite(tokens) 

233 

234 def _acquire_lock_safe(self) -> bool: 

235 """Safely acquire lock.""" 

236 try: 

237 return self._lock.acquire(timeout=0.1) 

238 except Exception: 

239 return False 

240 

241 def consume(self, tokens: float = 1.0) -> bool: 

242 """Try to consume tokens. 

243 

244 Args: 

245 tokens: Number of tokens to consume. Defaults to 1.0. 

246 

247 Returns: 

248 True if tokens were consumed (allow), False otherwise (limit exceeded). 

249 

250 """ 

251 if not self._is_valid_token_amount(tokens): 

252 return False 

253 if tokens <= 0: 

254 return True 

255 

256 if not self._acquire_lock_safe(): 

257 return False 

258 try: 

259 return self._process_consumption(tokens) 

260 finally: 

261 with contextlib.suppress(RuntimeError): 

262 self._lock.release() 

263 

264 

265class RateLimitDecorator(Protocol): 

266 """Protocol for the rate limit decorator.""" 

267 

268 @overload 

269 def __call__( 

270 self, 

271 func: Callable[P, T], 

272 ) -> Callable[P, Result[T, RateLimitError]]: ... 

273 

274 @overload 

275 def __call__( 

276 self, 

277 func: Callable[P, Awaitable[T]], 

278 ) -> Callable[P, Awaitable[Result[T, RateLimitError]]]: ... 

279 

280 

281def _async_rate_limit_wrapper( 

282 func_coro: Callable[P, Awaitable[T]], 

283 limiter: RateLimiter, 

284) -> Callable[P, Awaitable[Result[T, RateLimitError]]]: 

285 @functools.wraps(func_coro) 

286 async def async_wrapper( 

287 *args: P.args, 

288 **kwargs: P.kwargs, 

289 ) -> Result[T, RateLimitError]: 

290 try: 

291 if not limiter.consume(): 

292 return Err(RateLimitError()) 

293 except Exception: 

294 return Err(RateLimitError()) 

295 return Ok(await func_coro(*args, **kwargs)) 

296 

297 return async_wrapper 

298 

299 

300def _sync_rate_limit_wrapper( 

301 func_sync: Callable[P, T], 

302 limiter: RateLimiter, 

303) -> Callable[P, Result[T, RateLimitError]]: 

304 @functools.wraps(func_sync) 

305 def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, RateLimitError]: 

306 try: 

307 if not limiter.consume(): 

308 return Err(RateLimitError()) 

309 except Exception: 

310 return Err(RateLimitError()) 

311 return Ok(func_sync(*args, **kwargs)) 

312 

313 return wrapper 

314 

315 

316def rate_limit( 

317 max_calls: int, 

318 time_window: float, 

319) -> RateLimitDecorator: 

320 """Decorate a function to apply rate limiting. 

321 

322 If the rate limit is exceeded, the wrapped function immediately returns 

323 an ``Err(RateLimitError)``. Uses an in-memory token bucket strategy. 

324 

325 Args: 

326 max_calls: Maximum function executions allowed in the defined window. 

327 time_window: Time window size in seconds. 

328 

329 Returns: 

330 Decorated function returning a ``Result[T, RateLimitError]``. 

331 

332 Example: 

333 >>> @rate_limit(max_calls=2, time_window=1.0) 

334 ... def fetch_data() -> str: 

335 ... return "data" 

336 >>> fetch_data() 

337 Ok('data') 

338 >>> fetch_data() 

339 Ok('data') 

340 >>> fetch_data() 

341 Err(RateLimitError('Rate limit exceeded')) 

342 

343 """ 

344 

345 def decorator( 

346 func: Callable[P, T] | Callable[P, Awaitable[T]], 

347 ) -> ( 

348 Callable[P, Result[T, RateLimitError]] 

349 | Callable[P, Awaitable[Result[T, RateLimitError]]] 

350 ): 

351 limiter = RateLimiter(max_calls, time_window) 

352 

353 if inspect.iscoroutinefunction(func): 

354 func_coro = cast(Callable[P, Awaitable[T]], func) 

355 return _async_rate_limit_wrapper(func_coro, limiter) 

356 

357 func_sync = cast(Callable[P, T], func) 

358 return _sync_rate_limit_wrapper(func_sync, limiter) 

359 

360 return cast(RateLimitDecorator, decorator)