refactor!: uv 管理环境 + 彻底删除技术债(Flask 与 requests 全部移除)

## uv 环境管理
- pyproject.toml 声明 dependencies + [dependency-groups].dev,uv.lock 精确锁定
- 删除 requirements.txt / requirements-fastapi.txt / requirements-dev.txt
- .python-version = 3.12;Dockerfile 改用 uv sync --frozen(可复现构建)
- 新增 jinja2(首页渲染)

## 删除 Flask 技术债
- 从 main.py 用 ast 精确剥离 56 个 Flask 节点(路由/中间件/错误处理/启动),
  框架无关的服务层落为 services/runtime.py(MusicAPIService、下载/打包 worker、
  任务监控、缓存清扫),零 Flask 依赖
- 删除 main.py(4527 行)与 auth_routes.py(1050 行)
- auth_system.py 移除会话/请求上下文层(login_session/current_user/login_required/
  admin_required/_client_ip 等),保留数据与业务层
- 新增 core/net.py(IP 解析)、web/auth_state.py(登录锁定/2FA 票据/发码限流)
- FastAPI 侧改直接依赖 services.runtime,不再 import main
- web/app.py 去掉 Flask fallback;入口默认根路径模式(API_PREFIX 可选)

## 删除 requests 技术债
- 新增 core/sync_http.py:requests 风格的同步门面(底层 aiohttp 连接池,
  流式读取经有界队列背压),含 Session/headers/(connect,read) 元组超时兼容
- core/utils、auth_system、podcast_api、music_downloader、services 全部切换
- 实测真实下载 5.2MB 音频完整成功

## 质量门禁归零
- ruff:0 错误(B904 全部修复,不再忽略)
- pyright:0 错误(类型收窄修复)
- pytest:140/140(含 golden 契约回归、root 模式 66 项路径覆盖)
- 真实 uvicorn 启动:/health、/、/static、受保护端鉴权全部正确

新增 tests/golden/responses.json:删除 Flask 前捕获的 32 例响应快照,
FastAPI 逐字段复现——删除巨石后行为回归仍有硬证据。
This commit is contained in:
snowy-yang committed 2026-09-26 11:10:17 +08:00
1 parent f5d1e3c3a9
commit 8446166120
41 files changed
+4836 -6060

No files matched your search

+4 -4
View File
@@ -8,7 +8,7 @@
- POST /api/v1/auth/login ↔ Flask /auth/login(密码校验 + 失败锁定 + 管理员 2FA 转票据)
设计:
- 登录失败锁定与管理员 2FA 票据表**复用 auth_routes 的模块级状态**,两栈共享同一份
- 登录失败锁定与管理员 2FA 票据表**复用 web.auth_state 的模块级状态**,两栈共享同一份
计数/票据,避免「换个框架打就绕过锁定」。
- 密码校验(PBKDF2,10 万次迭代,CPU 密集)与库操作经 asyncio.to_thread 执行,
不阻塞事件循环。
@@ -104,7 +104,7 @@ async def ann_seen(user: Annotated[SiteUser | None, Depends(current_user)]):
@router.post('/auth/login')
async def login(request: Request):
"""登录:密码校验(含邮箱登录)、失败锁定、管理员两步验证转票据。"""
from auth_routes import (
from web.auth_state import (
_admin2fa_issue,
_admin2fa_mask,
_login_fail_check,
@@ -201,7 +201,7 @@ async def admin_login_email(request: Request):
"""管理员 2FA Step2:比对绑定邮箱 → 发送 admin2fa 验证码。"""
import hmac as _hmac
from auth_routes import (
from web.auth_state import (
_ADMIN2FA_LAST_SEND,
_ADMIN2FA_SEND_GAP,
_ADMIN_2FA,
@@ -245,7 +245,7 @@ async def admin_login_email(request: Request):
@router.post('/auth/admin_login/verify')
async def admin_login_verify(request: Request):
"""管理员 2FA Step3:验证码原子消费 → 建立管理员会话。"""
from auth_routes import (
from web.auth_state import (
_ADMIN_2FA,
_ADMIN_2FA_MAX_ATTEMPTS,
_admin2fa_take,
+14 -14
View File
@@ -115,8 +115,8 @@ async def download(user: Annotated[SiteUser | None, Depends(current_user)], requ
lyric_format = 'lrc'
need_zip = str(data.get('zip', 'false')).lower() in ('1', 'true', 'yes')
import main as legacy
downloader = legacy.api_service.downloader
import services.runtime as services
downloader = services.api_service.downloader
if return_format == 'json':
try:
@@ -127,7 +127,7 @@ async def download(user: Annotated[SiteUser | None, Depends(current_user)], requ
await billing.refund_open('rejected')
return error('获取失败:歌曲不存在或暂无版权', 404)
base = await asyncio.to_thread(
legacy._build_download_base, filename_format,
services._build_download_base, filename_format,
{'name': info.name, 'artist_string': info.artists})
filename = f'{base}.{info.file_type}'
try:
@@ -165,7 +165,7 @@ async def download(user: Annotated[SiteUser | None, Depends(current_user)], requ
# file 模式:注册后台任务
device_id = str(data.get('device_id') or '').strip()[:64]
await asyncio.to_thread(legacy._touch_device, device_id)
await asyncio.to_thread(services._touch_device, device_id)
task = _single_task(data, music_id, quality, filename_format, write_meta,
meta_fields, lyric_format, need_zip, cookies, ip, device_id)
reg_err = await register_download_task(billing, task, str(data.get('task_id') or '').strip())
@@ -173,7 +173,7 @@ async def download(user: Annotated[SiteUser | None, Depends(current_user)], requ
await billing.refund_open('rejected')
return error(reg_err, 429)
task_id = task['task_id']
start_err = await start_task(task_id, legacy._single_download_worker, (task_id,))
start_err = await start_task(task_id, services._single_download_worker, (task_id,))
if start_err:
return error(start_err, 500)
return success({'task_id': task_id, 'status': 'queued'}, '下载任务已提交')
@@ -248,8 +248,8 @@ async def download_batch_zip(user: Annotated[SiteUser | None, Depends(current_us
cookies = _cookies()
device_id = str(data.get('device_id') or '').strip()[:64]
import main as legacy
await asyncio.to_thread(legacy._touch_device, device_id)
import services.runtime as services
await asyncio.to_thread(services._touch_device, device_id)
task = {
'type': 'batch',
'total': len(ids), 'done': 0, 'failed': 0,
@@ -269,7 +269,7 @@ async def download_batch_zip(user: Annotated[SiteUser | None, Depends(current_us
await billing.refund_open('rejected')
return error(reg_err, 429)
task_id = task['task_id']
start_err = await start_task(task_id, legacy._batch_zip_worker, (task_id,))
start_err = await start_task(task_id, services._batch_zip_worker, (task_id,))
if start_err:
return error(start_err, 500)
return success({'task_id': task_id, 'status': 'queued', 'total': len(ids)},
@@ -330,8 +330,8 @@ async def podcast_download(user: Annotated[SiteUser | None, Depends(current_user
cookies = _cookies()
device_id = str(data.get('device_id') or '').strip()[:64]
import main as legacy
await asyncio.to_thread(legacy._touch_device, device_id)
import services.runtime as services
await asyncio.to_thread(services._touch_device, device_id)
task = {
'type': 'single',
'total': 1, 'done': 0, 'failed': 0,
@@ -346,7 +346,7 @@ async def podcast_download(user: Annotated[SiteUser | None, Depends(current_user
await billing.refund_open('rejected')
return error(reg_err, 429)
task_id = task['task_id']
start_err = await start_task(task_id, legacy._podcast_download_worker, (task_id,))
start_err = await start_task(task_id, services._podcast_download_worker, (task_id,))
if start_err:
return error(start_err, 500)
return success({'task_id': task_id, 'status': 'queued'}, '播客单集下载任务已提交')
@@ -402,8 +402,8 @@ async def podcast_batch_zip(user: Annotated[SiteUser | None, Depends(current_use
billed = _podcast_billing_count(data)
device_id = str(data.get('device_id') or '').strip()[:64]
import main as legacy
await asyncio.to_thread(legacy._touch_device, device_id)
import services.runtime as services
await asyncio.to_thread(services._touch_device, device_id)
task = {
'type': 'batch',
'total': 0, 'done': 0, 'failed': 0,
@@ -425,7 +425,7 @@ async def podcast_batch_zip(user: Annotated[SiteUser | None, Depends(current_use
await billing.refund_open('rejected')
return error(reg_err, 429)
task_id = task['task_id']
start_err = await start_task(task_id, legacy._podcast_zip_worker, (task_id,))
start_err = await start_task(task_id, services._podcast_zip_worker, (task_id,))
if start_err:
return error(start_err, 500)
return success({'task_id': task_id, 'status': 'queued'}, '播客打包任务已提交')
+3 -3
View File
@@ -11,7 +11,7 @@
说明:
- 同步的 auth_system 调用(SQLite 事务、邮件 SMTP、PBKDF2)经 asyncio.to_thread 执行,
不阻塞事件循环;行为与 Flask 完全一致。
- 发码 IP 限流复用 auth_routes 的模块级状态 `_SEND_CODE_IP`(跨栈共享计数)。
- 发码 IP 限流复用 web.auth_state 的模块级状态 `_SEND_CODE_IP`。
- 失败锁定/验证码消费等安全口径逐字保留。
"""
import asyncio
@@ -64,7 +64,7 @@ async def _safe_register_credits() -> int:
@router.post('/auth/send_code')
async def send_code(request: Request):
"""发送邮箱验证码(注册/找回用途隔离)。"""
from auth_routes import _send_code_ip_check
from web.auth_state import _send_code_ip_check
ip = ratelimit.client_ip(request)
if not _send_code_ip_check(ip):
return error('验证码请求过于频繁,请稍后再试')
@@ -141,7 +141,7 @@ async def forgot_password(request: Request):
@router.post('/auth/register')
async def register(request: Request):
"""注册:验证码校验 → 用户名/邮箱查重 → 防刷双闸 → 建号赠送 → 建立会话。"""
from auth_routes import re_username_ok
from web.auth_state import re_username_ok
data = await _request_data(request)
username = str(data.get('username') or '').strip()
+4 -4
View File
@@ -58,14 +58,14 @@ def _owned_by(task: dict[str, Any], user: SiteUser) -> bool:
def _semaphores():
"""批量打包/下载信号量(Flask 侧对象,懒取以共享同一计数)。"""
import main as legacy
return legacy.BATCH_ZIP_SEM, legacy.api_service.downloader._download_semaphore
import services.runtime as services
return services.BATCH_ZIP_SEM, services.api_service.downloader._download_semaphore
@router.api_route('/api/topen', methods=['GET', 'POST'])
async def topen(request: Request):
"""接口请求统计(实时)——锁内快照,避免 total 与明细不一致。"""
import main as legacy
import services.runtime as services
with STATS_LOCK:
snapshot = {p: dict(v) for p, v in REQUEST_STATS.items()}
endpoints = []
@@ -73,7 +73,7 @@ async def topen(request: Request):
for path, info in snapshot.items():
endpoints.append({
'path': path,
'name': legacy.ENDPOINT_NAMES.get(path, path),
'name': services.ENDPOINT_NAMES.get(path, path),
'count': info['count'],
'percent': round(info['count'] / total * 100, 1) if total else 0,
'last': info['last'],