refactor: auth_system 全面异步化(aiosqlite),拆掉 web/services 层的 to_thread 桥接

拆掉两类垫片的最后一处:auth_system 原为同步 sqlite3 栈,web 层与 services 的
worker 只能靠 asyncio.to_thread 逐个桥接才不阻塞事件循环——每次 DB 访问都白付一次
线程池调度,且「同步调异步」的边界散落在 100+ 个调用点。B1 已把 worker 变成协程,
本批把访问层本身也迁到原生异步,两条线在此合拢。

改动(按子系统):
- auth_system:db.py 照 core/db.py 现有范式重建为原生异步访问层(aiosqlite + WAL)
  ——读路径 _q 每次独立连接、无锁、可并发;写路径 _x / write_transaction 用
  asyncio.Lock 串行化,写者不阻塞读者。users / cards / credits / ledger / logs /
  settings / mail / geo / backup 九模块随之全部 async/await;security.py 是纯计算
  (pbkdf2/normalize)不动。__init__ 去掉 _DB_LOCK 与 get_conn 导出。
- web:app / deps / billing / tasks_registry 与 routers/{admin_site,auth,music,
  register,user} 直接 await,拆掉包裹的 to_thread。deps.secret_key 改 async,
  连带 _parse_cookie 也 async(会话解析要读密钥)。
- services:_taskcore / tasks / downloads / podcast 的账本调用与查询直接 await。
  4 处 start_task 调用点(download.py)确认已 await。

设计取舍(为什么这么做,而不是直接包一层):
- 锁按**事件循环**隔离(_LOOP_LOCKS 以 id(loop) 为键):asyncio.Lock 绑定创建它的
  loop,应用主 loop 与测试各自的 loop 并存,跨 loop 复用会抛 "bound to a different
  event loop"。
- WAL 切换用**独立锁** _wal_lock 而非 _write_lock:execute() 已持写锁,再在锁内
  connect→_configure 会自锁死(asyncio.Lock 非重入)。切换 + 标记在专用锁内串行并
  二次复查,否则并发首连会同时执行 PRAGMA journal_mode=WAL 争排他锁报
  database is locked(core/db.py 同款教训,实测复现)。
- force_wal 保留:journal_mode 持久化在库文件头,库文件被删重建时新文件不继承,
  必须重设。exists() 判定须在 aiosqlite.connect **之前**(connect 会创建空文件)。
- connect() 用 DB_PATH.parent 兜底建目录,优于 DATA_DIR:生产两者相同,但测试
  monkeypatch 只换 DB_PATH 时兜底仍能命中正确目录。

留在 to_thread 上的仅剩**正当的阻塞卸载**,不是同步门面:PBKDF2 的 10 万次迭代
(登录链路每次都要跑)、smtplib 发信、备份文件的 copy2 / os.replace、secret.key
的文件 IO。原有 aria2 / downloader / zip 侧的 to_thread 未动。

不变量逐条保持(迁移只改执行模型,不改语义):
- ledger_settle 幂等:账本非 open 直接 return 0,重启后重放不重复退款;
- 终态先到先得:_mark_task_terminal 对已 done/error/canceled 的任务直接 return,
  堵住 canceled→error 的非法迁移边;
- settle 必须在任务锁**外**调用(ledger_settle 要抢 SQLite 写锁,busy 最长 15s,
  持任务锁会让全站进度/提交/取消随库停摆);
- reserve_and_open 的预扣与开账同事务,消除原两步之间的崩溃丢账窗口。

路径真源红线:DATA_DIR / DB_PATH / BACKUP_DIR / SECRET_KEY_PATH 仍是 auth_system.db
的**模块全局**(用与 core.db 相同的表达式,但**不是**它的别名)。测试只 patch
auth_system.db.*,若改成 core.db 的别名会静默把测试写到生产库。已核 data/site.db
读写前后 sha256 完全一致。
顺带清掉 get_conn:迁移后它只剩「转调 connect()」一层空壳、全仓零消费者(测试
直接开裸连接、备份用 db.connect()),保留等于留一条「拿裸连接自己写」的口子。

测试:19 个文件同步迁移——10 个文件的 web.deps.secret_key 替身改 async;
test_db_conn.py 的多线程首连用例按异步语义拆成 2 条(单 loop gather(16) 覆盖批量
并发首连、WAL 就绪后 8 线程各自 loop 建连覆盖跨 loop);test_billing_scope.py 去掉
多余的 @pytest.mark.anyio;被 await 且**正常返回**的 monkeypatch 替身一律改 async
(仅 raise 的同步替身仍可用)。

门禁:ruff 全过 / pyright 0-0-0(standard 模式含 tests 与顶层模块)/ pytest
384 项全绿(0 失败 0 error 0 skipped;383→384 因 test_db_conn 拆用例)。
data/site.db 读写前后 sha256 一致(a19f5db…6487),无 -wal/-shm 边车残留。

下一步 B3:删 core/sync_http.py、core/async_bridge.py、core/http_errors.py 及
 tests/test_async_bridge.py——三者在生产侧已零消费者(http_errors 仅 sync_http
 自用,requests 已非声明依赖)。
This commit is contained in:
snowy-yang committed 2026-09-28 20:13:19 +08:00
1 parent 69a50c2c31
commit 96af56cc27
43 files changed
+1171 -1009

No files matched your search

+20 -21
View File
@@ -10,11 +10,10 @@
设计:
- 登录失败锁定与管理员 2FA 票据表**复用 web.auth_state 的模块级状态**,全进程共享同一份
计数/票据,避免「换个框架打就绕过锁定」。
- 密码校验(PBKDF2,10 万次迭代,CPU 密集)与库操作经 asyncio.to_thread 执行,
不阻塞事件循环。
- 密码校验(PBKDF2,10 万次迭代,CPU 密集)已在 auth_system.verify_login 内部经
asyncio.to_thread 卸载;其余 auth_system 调用已迁移为原生异步(aiosqlite)直接 await。
- 会话 Cookie 由 core.session 签发(沿用同一格式与密钥,存量会话继续有效),删 Cookie 亦同口径。
"""
import asyncio
import os
import time
from typing import Annotated
@@ -51,10 +50,10 @@ def _cookie_kwargs() -> dict:
'path': '/', 'secure': secure}
def _login_response(payload: dict, message: str, uid: int, seq: int) -> JSONResponse:
async def _login_response(payload: dict, message: str, uid: int, seq: int) -> JSONResponse:
"""构造带会话 Cookie 的成功响应(沿用同一 Cookie 格式)。"""
resp = JSONResponse(content={'status': 200, 'success': True, 'message': message, 'data': payload})
cookie = cs.dumps(deps.secret_key(), {
cookie = cs.dumps(await deps.secret_key(), {
'site_uid': uid, 'site_uid_seq': seq, 'site_uid_ts': int(time.time()),
})
resp.set_cookie(SESSION_COOKIE, cookie, **_cookie_kwargs())
@@ -109,7 +108,7 @@ async def _resolve_login_identity(username: str) -> tuple:
"""
if '@' not in username:
return None, username
iuser = await asyncio.to_thread(auth.get_user_by_email, username)
iuser = await auth.get_user_by_email(username)
lock_name = iuser['username'] if iuser else (auth._normalize_email(username) or username)
return iuser, lock_name
@@ -124,7 +123,7 @@ async def _allow_login_attempt(lock_name: str, ip: str) -> bool:
if _login_fail_check(lock_name):
return True
if _login_fail_locked_log_once(lock_name):
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
await auth.add_log('fail', lock_name, ip,
'登录', '失败次数过多,临时锁定')
return False
@@ -135,7 +134,7 @@ async def _check_account_status(user, lock_name: str, ip: str):
status = user['status'] if 'status' in keys else 1
if status == 2:
reason = user['ban_reason'] if 'ban_reason' in keys else ''
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
await auth.add_log('fail', lock_name, ip,
'登录', f'封禁账号尝试登录: {reason}')
return error('账号已被封禁' + (f':{reason}' if reason else '') + ',请联系管理员')
if status == 0:
@@ -152,11 +151,11 @@ async def _admin_two_factor_response(user, lock_name: str, ip: str) -> JSONRespo
admin_email = user['email'] if 'email' in user.keys() else ''
if not admin_email:
await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip,
await auth.add_log('fail', lock_name, ip,
'管理员登录', '未绑定邮箱,两步验证不可用')
return error('管理员账号未绑定邮箱,请联系管理员先完成绑定')
ticket = _admin2fa_issue(user)
await asyncio.to_thread(auth.add_log, 'success', lock_name, ip,
await auth.add_log('success', lock_name, ip,
'管理员登录', '密码验证通过,待邮箱验证')
return success({'ticket': ticket, 'email_masked': _admin2fa_mask(admin_email),
'username': user['username'], 'admin_2fa': True},
@@ -180,7 +179,7 @@ async def _user_session_response(user, ip: str) -> JSONResponse:
return error('检测到账号在多个省份异常登录,已自动封禁,请联系管理员')
fresh = await repo.get_user_by_id(uid) or {}
return _login_response({
return await _login_response({
'user': _user_public(fresh),
'duration_text': _format_credits(int(fresh.get('duration_seconds') or 0)),
'redirect': 'admin' if fresh.get('role') == 'admin' else 'user',
@@ -209,7 +208,7 @@ async def login(request: Request):
return error('尝试过于频繁,该账号已临时锁定,请 10 分钟后再试')
verify_name = iuser['username'] if iuser is not None else username
user = await asyncio.to_thread(auth.verify_login, verify_name, password)
user = await auth.verify_login(verify_name, password)
if not user:
from web.auth_state import _login_fail_record
_login_fail_record(lock_name)
@@ -256,7 +255,7 @@ async def admin_login_email(request: Request):
if (not email_input or not v.get('email')
or not _hmac.compare_digest(email_input, v['email'])):
v['attempts'] += 1
await asyncio.to_thread(auth.add_log, 'fail', v['username'], ip, '管理员登录', '绑定邮箱不匹配')
await auth.add_log('fail', v['username'], ip, '管理员登录', '绑定邮箱不匹配')
if v['attempts'] >= _ADMIN_2FA_MAX_ATTEMPTS:
_ADMIN_2FA.pop(ticket, None)
return error('错误次数过多,请重新开始登录')
@@ -266,9 +265,9 @@ async def admin_login_email(request: Request):
if time.time() - last_send < _ADMIN2FA_SEND_GAP:
return error('验证码发送过于频繁,请 1 分钟后再试')
try:
await asyncio.to_thread(auth.send_verify_code, v['email'], 'admin2fa')
await auth.send_verify_code(v['email'], 'admin2fa')
_ADMIN2FA_LAST_SEND[v['username']] = time.time()
await asyncio.to_thread(auth.add_log, 'success', v['username'], ip, '管理员登录',
await auth.add_log('success', v['username'], ip, '管理员登录',
f'绑定邮箱验证通过,验证码已发送({_admin2fa_mask(v["email"])})')
return success(message='验证码已发送至管理员邮箱,请查收')
except (ValueError, RuntimeError) as e:
@@ -293,22 +292,22 @@ async def admin_login_verify(request: Request):
return error('登录会话已过期,请重新开始登录', 401, error_code='admin_2fa_expired')
code = str(data.get('code') or '').strip()
if not await asyncio.to_thread(auth.check_verify_code, v['email'], code, 'admin2fa'):
if not await auth.check_verify_code(v['email'], code, 'admin2fa'):
v['attempts'] += 1
if v['attempts'] >= _ADMIN_2FA_MAX_ATTEMPTS:
_ADMIN_2FA.pop(ticket, None)
return error('错误次数过多,请重新开始登录')
await asyncio.to_thread(auth.add_log, 'fail', v['username'], ip, '管理员登录', '验证码错误')
await auth.add_log('fail', v['username'], ip, '管理员登录', '验证码错误')
return error('验证码错误或已过期')
_ADMIN_2FA.pop(ticket, None) # 一次性
user = await asyncio.to_thread(auth.get_user_by_id, v['user_id'])
user = await auth.get_user_by_id(v['user_id'])
if not user or user['role'] != 'admin':
return error('登录会话已过期,请重新开始登录', 401, error_code='admin_2fa_expired')
keys = user.keys()
status = user['status'] if 'status' in keys else 1
if status == 2:
await asyncio.to_thread(auth.add_log, 'fail', v['username'], ip, '管理员登录', '封禁账号尝试登录')
await auth.add_log('fail', v['username'], ip, '管理员登录', '封禁账号尝试登录')
return error('账号已被封禁,请联系管理员')
if status == 0:
return error('账号已被禁用,请联系管理员')
@@ -326,8 +325,8 @@ async def admin_login_verify(request: Request):
return error('检测到账号在多个省份异常登录,已自动封禁,请联系管理员')
fresh = await repo.get_user_by_id(uid) or {}
await asyncio.to_thread(auth.add_log, 'success', v['username'], ip, '管理员登录', '两步验证通过')
return _login_response({
await auth.add_log('success', v['username'], ip, '管理员登录', '两步验证通过')
return await _login_response({
'user': _user_public(fresh),
'duration_text': _format_credits(int(fresh.get('duration_seconds') or 0)),
'redirect': 'admin',