Spaces:
Running
Running
Download app/cache.py from Reaper1909/wade-ips: direct link, hf CLI and curl.
- Browser
- Download file 3.81 kB
-
https://huggingface.co/spaces/Reaper1909/wade-ips/resolve/main/app/cache.py
- Command line
-
hf download hf://spaces/Reaper1909/wade-ips/app/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/Reaper1909/wade-ips/resolve/main/app/cache.py
3.81 kB
| """Verdict cache and rate limiter, each with an in-process and a Redis implementation. | |
| The in-process versions are bounded (LRU + TTL) so memory can never grow without limit; the | |
| Redis versions are used automatically when REDIS_URL is set so several API replicas share state. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import time | |
| from collections import OrderedDict | |
| from typing import Any, Callable | |
| class MemoryCache: | |
| """Bounded LRU cache with per-item TTL.""" | |
| def __init__(self, max_items: int = 500, ttl: int = 3600, clock: Callable[[], float] = time.monotonic): | |
| self.max_items, self.ttl, self._clock = max_items, ttl, clock | |
| self._data: OrderedDict[str, tuple[float, Any]] = OrderedDict() | |
| def __len__(self) -> int: | |
| return len(self._data) | |
| async def get(self, key: str) -> Any | None: | |
| item = self._data.get(key) | |
| if item is None: | |
| return None | |
| expires, value = item | |
| if expires <= self._clock(): | |
| self._data.pop(key, None) | |
| return None | |
| self._data.move_to_end(key) | |
| return value | |
| async def set(self, key: str, value: Any) -> None: | |
| self._data[key] = (self._clock() + self.ttl, value) | |
| self._data.move_to_end(key) | |
| while len(self._data) > self.max_items: | |
| self._data.popitem(last=False) | |
| class RedisCache: | |
| def __init__(self, client, ttl: int = 3600, prefix: str = "wade:v1:"): | |
| self._r, self.ttl, self._p = client, ttl, prefix | |
| async def get(self, key: str) -> Any | None: | |
| raw = await self._r.get(self._p + key) | |
| return json.loads(raw) if raw else None | |
| async def set(self, key: str, value: Any) -> None: | |
| await self._r.set(self._p + key, json.dumps(value), ex=self.ttl) | |
| class MemoryRateLimiter: | |
| """Sliding-window limiter: at most `limit` calls per `window` seconds per key.""" | |
| def __init__(self, limit: int = 60, window: int = 60, clock: Callable[[], float] = time.monotonic): | |
| self.limit, self.window, self._clock = limit, window, clock | |
| self._hits: dict[str, list[float]] = {} | |
| async def check(self, key: str) -> tuple[bool, int]: | |
| """Return (allowed, retry_after_seconds).""" | |
| now = self._clock() | |
| hits = [t for t in self._hits.get(key, []) if t > now - self.window] | |
| if len(hits) >= self.limit: | |
| self._hits[key] = hits | |
| return False, max(1, int(hits[0] + self.window - now) + 1) | |
| hits.append(now) | |
| self._hits[key] = hits | |
| if len(self._hits) > 10_000: # bound memory: drop idle keys | |
| for k in [k for k, v in self._hits.items() if not v or v[-1] <= now - self.window]: | |
| self._hits.pop(k, None) | |
| return True, 0 | |
| class RedisRateLimiter: | |
| """Fixed-window limiter shared across replicas (INCR + EXPIRE).""" | |
| def __init__(self, client, limit: int = 60, window: int = 60, prefix: str = "wade:rl:"): | |
| self._r, self.limit, self.window, self._p = client, limit, window, prefix | |
| async def check(self, key: str) -> tuple[bool, int]: | |
| bucket = int(time.time() // self.window) | |
| k = f"{self._p}{key}:{bucket}" | |
| count = await self._r.incr(k) | |
| if count == 1: | |
| await self._r.expire(k, self.window + 1) | |
| if count > self.limit: | |
| return False, self.window - int(time.time() % self.window) or 1 | |
| return True, 0 | |
| def make_cache_and_limiter(settings, redis_client=None): | |
| if redis_client is not None: | |
| return (RedisCache(redis_client, ttl=settings.cache_ttl_seconds), | |
| RedisRateLimiter(redis_client, limit=settings.rate_limit_per_min)) | |
| return (MemoryCache(settings.cache_max_items, settings.cache_ttl_seconds), | |
| MemoryRateLimiter(settings.rate_limit_per_min)) | |