|
| 1 | +""" |
| 2 | +ContentPipe — 简易 API 速率限制 |
| 3 | +
|
| 4 | +基于 IP 的滑动窗口计数器,无外部依赖。 |
| 5 | +通过 CONTENTPIPE_RATE_LIMIT 环境变量控制(默认:60/min)。 |
| 6 | +设为 0 或空值表示不限制。 |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import os |
| 12 | +import time |
| 13 | +from collections import defaultdict |
| 14 | +from typing import Callable |
| 15 | + |
| 16 | +from fastapi import Request |
| 17 | +from fastapi.responses import JSONResponse |
| 18 | +from starlette.middleware.base import BaseHTTPMiddleware |
| 19 | + |
| 20 | + |
| 21 | +def _parse_rate_limit() -> tuple[int, int]: |
| 22 | + """解析速率限制配置,格式: '{count}/{period}' 例如 '60/min' '100/hour'""" |
| 23 | + raw = os.environ.get("CONTENTPIPE_RATE_LIMIT", "60/min").strip() |
| 24 | + if not raw or raw == "0": |
| 25 | + return 0, 0 |
| 26 | + |
| 27 | + try: |
| 28 | + count_str, period_str = raw.split("/", 1) |
| 29 | + count = int(count_str) |
| 30 | + periods = {"sec": 1, "min": 60, "hour": 3600, "day": 86400} |
| 31 | + period = periods.get(period_str, 60) |
| 32 | + return count, period |
| 33 | + except Exception: |
| 34 | + return 60, 60 # 默认 60/min |
| 35 | + |
| 36 | + |
| 37 | +class RateLimitMiddleware(BaseHTTPMiddleware): |
| 38 | + """基于 IP 的简易速率限制""" |
| 39 | + |
| 40 | + def __init__(self, app, max_requests: int = 0, window_seconds: int = 60): |
| 41 | + super().__init__(app) |
| 42 | + if max_requests == 0: |
| 43 | + limit, window = _parse_rate_limit() |
| 44 | + self.max_requests = limit |
| 45 | + self.window = window |
| 46 | + else: |
| 47 | + self.max_requests = max_requests |
| 48 | + self.window = window_seconds |
| 49 | + self._hits: dict[str, list[float]] = defaultdict(list) |
| 50 | + |
| 51 | + async def dispatch(self, request: Request, call_next): |
| 52 | + if self.max_requests <= 0: |
| 53 | + return await call_next(request) |
| 54 | + |
| 55 | + # 只限制 API 写入端点 |
| 56 | + path = request.url.path |
| 57 | + if not path.startswith("/api/") or request.method in ("GET", "HEAD", "OPTIONS"): |
| 58 | + return await call_next(request) |
| 59 | + |
| 60 | + client_ip = request.client.host if request.client else "unknown" |
| 61 | + now = time.time() |
| 62 | + cutoff = now - self.window |
| 63 | + |
| 64 | + # 清理过期记录 |
| 65 | + hits = self._hits[client_ip] |
| 66 | + self._hits[client_ip] = [t for t in hits if t > cutoff] |
| 67 | + hits = self._hits[client_ip] |
| 68 | + |
| 69 | + if len(hits) >= self.max_requests: |
| 70 | + retry_after = int(hits[0] - cutoff) + 1 |
| 71 | + return JSONResponse( |
| 72 | + {"detail": "Rate limit exceeded", "retry_after": retry_after}, |
| 73 | + status_code=429, |
| 74 | + headers={"Retry-After": str(retry_after)}, |
| 75 | + ) |
| 76 | + |
| 77 | + hits.append(now) |
| 78 | + return await call_next(request) |
0 commit comments