feat(routes): 迁移查询类路由到 FastAPI + 会话互通 + 统一错误/限流

会话互通(迁移关键):
- core/session.py:itsdangerous 兼容的签名 Cookie 编解码(同密钥/同 salt/同
  时间戳编码),Flask 与 FastAPI 双向可读——实测 F->core 与 core->F 双向解出一致,
  篡改/错密钥返回 None

FastAPI 基础设施:
- web/deps.py    会话→当前用户(封禁/顶号校验,口径同 auth_system.current_user)
- web/errors.py  AppError + 全局异常处理,404/405/400 统一为本站包体
- web/ratelimit.py 复用 core.state 同一批限流桶(跨栈共享,避免绕框架绕过限流)
- core/repo.py  补 get_user_by_id(异步)

迁移路由(/api/v1/*,与 Flask 同端点逐字段对齐):
- toplist / artist_songs / comments / search,走 music_api 异步方法
- search 的服务器昵称遮蔽改为 FastAPI 侧异步实现(不再依赖 main)

契约奇偶校验:扩展至 7 项(含登录会话互通 + 未登录 401),全 OK;
CDN 分片主机差异归一化(上游易变值,非契约漂移)。

验证:pytest 33/33;ruff All checks passed;pyright 0 errors;
uvicorn 实跑未登录 401 包体与 Flask 一致。
This commit is contained in:
snowy-yang committed 2026-09-26 01:09:01 +08:00
1 parent c77ef40fd5
commit 2c55b55e03
9 files changed
+559 -6

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*-
"""公网限流(FastAPI 栈)——按 IP 滑动窗口,与 Flask 侧 _rate_ok 同一实现口径。
复用 core.state.RATE_BUCKETS/_RATE_LOCK,使两栈在迁移期共享同一批限流桶
(同一 IP 无论打到哪个栈都计入同一窗口),避免出现「绕到另一个框架即绕过限流」。
"""
import collections
import time
from fastapi import Request
from core.config import RESULT_RETENTION_SECONDS # noqa: F401 - 保持与 Flask 侧常量同源
from core.state import RATE_BUCKETS, RATE_LOCK
from web.errors import AppError
# 免于限流的端点(试听流/进度轮询,与 Flask _QUIET/_rate_limit_guard 同口径)
_EXEMPT_PREFIXES = ('/audio_stream',)
_EXEMPT_PATHS = {'/api/queue', '/api/batch_progress', '/api/task/heartbeat'}
def client_ip(request: Request) -> str:
"""客户端 IP:仅当直连方是回环(可信反代)时采信 XFF/Real-IP,与 Flask 同策略。"""
import auth_system
remote = request.client.host if request.client else '-'
if remote and remote != '-' and auth_system._is_loopback_ip(remote):
xff = request.headers.get('x-forwarded-for')
if xff:
ip = auth_system._trusted_proxy_ip(xff)
if ip and not auth_system._is_loopback_ip(ip):
return ip
xreal = request.headers.get('x-real-ip')
if xreal:
ip = auth_system._trusted_proxy_ip(xreal)
if ip:
return ip
return remote or '-'
def rate_ok(key: str, limit: int, window: int) -> bool:
"""滑动窗口限流:True=放行。与 Flask main._rate_ok 同算法、同桶容器。"""
now = time.time()
with RATE_LOCK:
dq = RATE_BUCKETS.get(key)
if dq is None:
if len(RATE_BUCKETS) > 8000:
for k in [k for k, v in RATE_BUCKETS.items() if not v or now - v[-1] > window]:
RATE_BUCKETS.pop(k, None)
dq = collections.deque()
RATE_BUCKETS[key] = dq
while dq and now - dq[0] > window:
dq.popleft()
if len(dq) >= limit:
return False
dq.append(now)
return True
async def guard(request: Request, *, bucket: str, limit: int, window: int) -> None:
"""限流闸:超限抛 429(与 Flask 包体同形)。豁免端点直接放行。"""
path = request.url.path
if path in _EXEMPT_PATHS or path.startswith(_EXEMPT_PREFIXES):
return
if not rate_ok(f'{bucket}:' + client_ip(request), limit, window):
raise AppError('请求过于频繁,请稍后再试', 429)