refactor: worker 子系统全面异步化,拆掉同步转异步的桥接层

拆掉「同步调异步 / 异步桥同步」两类垫片的第二半(HTTP 线 B2 见前序提交)。
worker 侧此前是「起线程跑同步函数、函数体内部再用 asyncio.to_thread 把活塞给
另一条循环」——线程与协程互等,取消/暂停只能靠轮询。本轮把 worker 自身变成
协程,由 _start_task 直接挂到应用事件循环上,桥接层随之失去存在理由。

改动(按子系统):
- music_downloader:downloader / _aria2 / _concurrency / cover / _http /
  __main__ 全链路协程化。per-file 锁改 asyncio.Lock;计数闸改
  「active 计数 + await asyncio.sleep(0.5)」的可取消等待(原阻塞式 with 会让
  已取消任务仍要等全局名额腾出,卡死并拖后腿退款);aria2p 的同步 RPC 仍经
  to_thread,轮询改 asyncio.sleep;新增 core.http_client.iter_chunks,把**流式
  读取期**的 aiohttp.ClientError 收敛成 UpstreamNetworkError(请求建立阶段早已
  有这条路径,读取阶段此前没有,断流会绕过调用方的 UpstreamError 分类)。
  删除 get_http_session / _SESSION_LOCAL。
  models._RetryFromScratch 不再继承 requests.RequestException 而继承 Exception:
  它是「续传起点失效、残片已清、从头重下」,既不是确定性失败
  (DownloadException),也不是残片已保留的网络失败(UpstreamError),必须独立
  成类且在 except 链中先于二者捕获。
- music_api:podcast.py 全部函数协程化(直链解析内部改
  await NeteaseAPI.get_song_url);compat.py 删除——16 个死掉的同步门面早已
  清空,文件只剩空壳。
- services:_taskcore / _zipcore / batch / downloads / podcast / tasks 协程化。
  threading.Thread → loop.create_task(任务句柄字段 worker_thread →
  worker_task),ThreadPoolExecutor → asyncio.gather + asyncio.Semaphore,
  终态函数与结算回调全部改 await;监控线程里「worker 已死」判定改 task.done()。
  删除 services/streaming.py(同步流垫片,唯一消费者已迁到
  core.http_client.open)。zipfile 实例仍非线程安全,故「下载」并行、
  「入包」严格串行。
- web:路由层 130+ 处 to_thread 拆除——被包住的目标自己已是协程,再包一层只是
  把协程丢进线程里跑一圈。tasks_registry.start_task 直接 create_task。
  web/app.py 关闭段去掉 async_bridge.shutdown()(不再有第二条约循环)。
  web/routers/download.py 的播客端点补上 3 处漏掉的 await
  (extract_podcast_ref / get_radio_detail)——漏掉时不报错、只静默返回协程对象,
  靠 pyright 抓出来后修正。

留在 to_thread 上的都是**正当的阻塞卸载**:同步 SQLite 落库与账本结算、
mutagen 全量重写标签、zipfile 整段拷贝、shutil.rmtree、aria2p 的同步 RPC、
PBKDF2 的 10 万次迭代。ruff 对残留的本地元数据操作(exists/stat/os.replace/
往 .part 顺序写分块)按「微秒级、卸载的调度开销大于操作本身」放行,pyproject
逐条注明理由。

取消/暂停仍由 threading.Event 承载:置位方是请求线程/监控线程,读取方是 worker
协程,只有「置位」与「轮询读取」两种操作,既不需要跨循环唤醒也不会卡住事件
循环——比 asyncio.Event 更省心(ASYNC110 同理按此豁免)。

测试:10 个文件的替身边界同步迁移——网络替身从 core.sync_http 的
get_http_session 换成 downloader/服务模块的 _http.open + **真实** iter_chunks
(顺带钉住读取期异常收敛);`_run` 改为在独立线程里 asyncio.run(worker(...));
aria2 的假时钟从 time.sleep 换成 _POLL_INTERVAL=0;monitor 的线程句柄替身换成
done() 可控的轻量替身(asyncio.Task 的构造需要运行中的事件循环,而监控循环跑在
常驻线程里);podcast / 封面 / 结算包装等替身一律改 async。

门禁:ruff 全过 / pyright 0-0 / pytest 383 项全绿(0 失败)。

下一步 B2:auth_system 12 个模块改 aiosqlite 背板、web 层剩余 to_thread 收尾;
B3:删 core/sync_http.py、core/async_bridge.py、core/http_errors.py(现仅
sync_http 自用)。
This commit is contained in:
snowy-yang committed 2026-09-28 19:36:56 +08:00
1 parent 65adfc9089
commit 69a50c2c31
35 files changed
+1062 -1005

No files matched your search

+2 -5
View File
@@ -40,7 +40,7 @@ def _make_lifespan(start_monitor: bool):
@asynccontextmanager
async def _lifespan(app: FastAPI):
"""应用生命周期:建表 → 启动任务监控 → 关闭时释放连接池与后台 loop。
"""应用生命周期:建表 → 启动任务监控 → 关闭时释放连接池。
启动必须建表。全新部署时宿主机的 data/ 往往是个空目录(compose 用
`./data:/app/data` 挂载,会盖掉镜像内的任何内容),此时若只等首次查询
@@ -62,12 +62,9 @@ def _make_lifespan(start_monitor: bool):
await asyncio.to_thread(start_task_monitor)
yield
try:
from core import async_bridge, http_client
from core import http_client
await http_client.client.close()
# 停掉 sync↔async 桥的后台事件循环(daemon 线程不调也能随进程退出,
# 但显式关闭更干净)
async_bridge.shutdown()
except Exception:
pass
+12 -15
View File
@@ -12,7 +12,6 @@
settle/rename 消费过的行天然豁免);任务登记与启动由 web.tasks_registry 承担;
worker 复用 services 层既有实现,账本与交付语义不变。
"""
import asyncio
import logging
import threading
import time
@@ -72,19 +71,17 @@ async def _sync_download_json(downloader, music_id: str, quality: str, cookies:
只负责在成功路径 settle(1, 'delivered')(结算后自动退自然豁免)。
"""
try:
info = await asyncio.to_thread(
downloader.get_music_info, int(music_id), quality, cookies)
info = await downloader.get_music_info(int(music_id), quality, cookies)
except Exception as e:
logger.error('获取音乐信息失败: %s', e)
return error('获取失败:歌曲不存在或暂无版权', 404)
from services._shared import _build_download_base
base = await asyncio.to_thread(
_build_download_base, filename_format,
{'name': info.name, 'artist_string': info.artists})
base = _build_download_base(
filename_format, {'name': info.name, 'artist_string': info.artists})
filename = f'{base}.{info.file_type}'
try:
dl = await asyncio.to_thread(
downloader.download_music_file, int(music_id), quality,
dl = await downloader.download_music_file(
int(music_id), quality,
write_meta=write_meta, meta_fields=meta_fields,
cookies=cookies, music_info=info)
if not dl.success:
@@ -190,7 +187,7 @@ async def download(user: Annotated[SiteUser | None, Depends(current_user)], requ
from services import downloads as services_downloads
from services import tasks as services_tasks
device_id = str(data.get('device_id') or '').strip()[:64]
await asyncio.to_thread(services_tasks._touch_device, device_id)
services_tasks._touch_device(device_id)
task = _single_task({
'music_id': music_id, 'quality': quality,
'filename_format': filename_format, 'write_meta': write_meta,
@@ -273,7 +270,7 @@ async def download_batch_zip(user: Annotated[SiteUser | None, Depends(current_us
device_id = str(data.get('device_id') or '').strip()[:64]
from services import batch as services_batch
from services import tasks as services_tasks
await asyncio.to_thread(services_tasks._touch_device, device_id)
services_tasks._touch_device(device_id)
task = {
'type': 'batch',
'total': len(ids), 'done': 0, 'failed': 0,
@@ -337,7 +334,7 @@ async def podcast_download(user: Annotated[SiteUser | None, Depends(current_user
from music_api import podcast
quality = _podcast_quality(data)
need_zip = str(data.get('zip', 'false')).lower() in ('1', 'true', 'yes')
ref = podcast.extract_podcast_ref(raw)
ref = await podcast.extract_podcast_ref(raw)
if ref['kind'] == 'radio':
return error('这是电台链接,请先解析电台后选择单集下载,或使用「打包整个播客」')
@@ -352,7 +349,7 @@ async def podcast_download(user: Annotated[SiteUser | None, Depends(current_user
device_id = str(data.get('device_id') or '').strip()[:64]
from services import podcast as services_podcast
from services import tasks as services_tasks
await asyncio.to_thread(services_tasks._touch_device, device_id)
services_tasks._touch_device(device_id)
task = {
'type': 'single',
'total': 1, 'done': 0, 'failed': 0,
@@ -403,13 +400,13 @@ async def podcast_batch_zip(user: Annotated[SiteUser | None, Depends(current_use
from music_api import podcast
if raw_radio:
ref = podcast.extract_podcast_ref(raw_radio)
ref = await podcast.extract_podcast_ref(raw_radio)
if ref['kind'] == 'program':
return error('这是单集链接,请使用「下载单集」或直接输入电台链接/ID')
radio_id = ref['id']
radio_name = ''
try:
radio_name = podcast.get_radio_detail(radio_id, cookies).get('name', '')
radio_name = (await podcast.get_radio_detail(radio_id, cookies)).get('name', '')
except APIException:
pass
else:
@@ -423,7 +420,7 @@ async def podcast_batch_zip(user: Annotated[SiteUser | None, Depends(current_use
device_id = str(data.get('device_id') or '').strip()[:64]
from services import podcast as services_podcast
from services import tasks as services_tasks
await asyncio.to_thread(services_tasks._touch_device, device_id)
services_tasks._touch_device(device_id)
task = {
'type': 'batch',
'total': 0, 'done': 0, 'failed': 0,
+10 -16
View File
@@ -7,10 +7,9 @@
- POST/GET /api/v1/podcast/search ↔ Flask /podcast/search
- POST/GET /api/v1/podcast/hot ↔ Flask /podcast/hot
说明:music_api.podcast 是同步模块(底层 core.sync_http),此处以 asyncio.to_thread 包装,
让阻塞的上游调用不占用事件循环——行为不变,且不阻塞其它请求。
说明:music_api.podcast 是原生异步模块(底层 core.http_client),此处直接 await;
解析与直链检查同属一次请求,不再需要线程卸载。
"""
import asyncio
from typing import Annotated
from fastapi import APIRouter, Depends, Request
@@ -51,8 +50,7 @@ async def podcast_parse(_user: LoginUser, request: Request):
cookies = _cookies()
try:
result = await asyncio.to_thread(
podcast.parse_podcast_ref, raw, cookies, page_size=page_size)
result = await podcast.parse_podcast_ref(raw, cookies, page_size=page_size)
except APIException as e:
return error(str(e), 404)
except Exception:
@@ -64,8 +62,7 @@ async def podcast_parse(_user: LoginUser, request: Request):
url_info = None
if song_id:
try:
url_info = await asyncio.to_thread(
podcast.resolve_episode_url, song_id, cookies, quality)
url_info = await podcast.resolve_episode_url(song_id, cookies, quality)
except Exception:
url_info = None
if url_info:
@@ -110,9 +107,8 @@ async def podcast_programs(_user: LoginUser, request: Request):
if not str(radio_id).isdigit():
return error('无效的电台 ID')
try:
result = await asyncio.to_thread(
podcast.get_radio_programs, radio_id, _cookies(),
limit=limit, offset=offset, asc=asc)
result = await podcast.get_radio_programs(radio_id, _cookies(),
limit=limit, offset=offset, asc=asc)
return success(result, '获取单集列表成功')
except APIException as e:
return error(str(e), 404)
@@ -134,9 +130,8 @@ async def podcast_search(_user: LoginUser, request: Request):
if search_type not in ('all', 'radio', 'voice'):
search_type = 'all'
try:
result = await asyncio.to_thread(
podcast.search_podcast, keyword, _cookies(),
limit=limit, offset=offset, search_type=search_type)
result = await podcast.search_podcast(keyword, _cookies(),
limit=limit, offset=offset, search_type=search_type)
return success(result, '播客搜索完成')
except APIException as e:
return error(str(e), 404)
@@ -153,14 +148,13 @@ async def podcast_hot(_user: LoginUser, request: Request):
offset = max(0, _safe_int(data.get('offset'), 0))
cate_id = data.get('cate_id') or None
try:
radios = await asyncio.to_thread(
podcast.get_hot_radios, _cookies(), limit=limit, offset=offset, cate_id=cate_id)
radios = await podcast.get_hot_radios(_cookies(), limit=limit, offset=offset, cate_id=cate_id)
except APIException as e:
return error(str(e), 404)
except Exception:
return error('服务暂时不可用,请稍后再试', 500)
try:
categories = await asyncio.to_thread(podcast.get_categories)
categories = await podcast.get_categories()
except APIException:
categories = []
# 满页视为可能还有更多
+2 -3
View File
@@ -12,7 +12,6 @@
这些端点读写 core.state 的共享任务表(与任务执行侧同一批对象),因此
看到的是同一份任务状态。
"""
import asyncio
import time
from typing import Annotated, Any
@@ -173,7 +172,7 @@ async def task_heartbeat(user: LoginUser, request: Request):
device_id = str(data.get('device_id') or '').strip()[:64]
if not device_id:
return error('缺少 device_id 参数')
await asyncio.to_thread(services_tasks._touch_device, device_id)
services_tasks._touch_device(device_id)
resumed = 0
with DOWNLOAD_TASKS_LOCK:
for task in DOWNLOAD_TASKS.values():
@@ -199,7 +198,7 @@ async def task_list(user: LoginUser, request: Request):
device_id = str(data.get('device_id') or '').strip()[:64]
if not device_id:
return error('缺少 device_id 参数')
await asyncio.to_thread(services_tasks._touch_device, device_id)
services_tasks._touch_device(device_id)
my_tasks = []
with DOWNLOAD_TASKS_LOCK:
for tid, task in DOWNLOAD_TASKS.items():
+9 -6
View File
@@ -7,7 +7,7 @@
import logging
import re
import uuid
from collections.abc import Callable
from collections.abc import Awaitable, Callable
from typing import Any
from core.config import MAX_ACTIVE_TASKS_PER_USER, MAX_TERMINAL_TASKS, MAX_TOTAL_TASKS
@@ -71,9 +71,12 @@ async def register_download_task(billing: Billing, task: dict[str, Any],
return None
async def start_task(task_id: str, worker: Callable, args: tuple = ()) -> str | None:
"""启动 worker 线程(复用 services 的 _start_task_thread,失败收敛终态并退费)。"""
import asyncio
async def start_task(task_id: str, worker: Callable[..., Awaitable[None]],
args: tuple = ()) -> str | None:
"""启动 worker 协程(复用 services 的 _start_task,失败收敛终态并退费)。
from services._taskcore import _start_task_thread
return await asyncio.to_thread(_start_task_thread, task_id, worker, args)
worker 已是协程函数:直接作为 asyncio 任务挂到当前事件循环(不再起线程),
任务句柄记在任务字典里供监控循环判断「worker 已结束但没人结算」的兜底场景。
"""
from services._taskcore import _start_task
return _start_task(task_id, worker, args)