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

+89 -71
View File
@@ -4,7 +4,12 @@
整台打包的骨架(状态机 / 暂停 / 名额 / 终态收敛 / 结算)在
:mod:`services._zipcore`,本模块只保留播客侧策略:清单组装(整台或指定单集)、
逐集顺序下载、按实际集数补扣、单条目入包(首集附封面)。
下载走 core.http_client 的流式响应(原先是 services.streaming 这个同步流垫片),
落盘写文件是阻塞 IO、ZIP 组装是整段拷贝,均经 ``asyncio.to_thread`` 卸载。
"""
import asyncio
import os
import shutil
import tempfile
@@ -17,6 +22,8 @@ from pathlib import Path
from typing import Any
import auth_system
from core.http_client import client as _http
from core.http_client import iter_chunks
from core.state import (
DOWNLOAD_TASKS,
DOWNLOAD_TASKS_LOCK,
@@ -49,9 +56,13 @@ from .api_service import (
from .downloads import (
_abort_if_canceled,
)
from .streaming import (
_stream_open,
)
# 播客流式下载的上游头(与音频直链 CDN 的口径一致)
_STREAM_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Safari/537.36',
'Referer': 'https://music.163.com/',
}
def _podcast_safe_name(s: str, fallback: str = 'unknown') -> str:
@@ -92,20 +103,21 @@ def _report_progress(task_id: str, progress_label: str, done: int, total: int) -
t['live_percent'] = min(99.0, float(pct))
def _stream_to_part(url: str, part: Path, total_size: int, cancel_ev: threading.Event,
task_id: str, progress_label: str) -> tuple[int, int]:
async def _stream_to_part(url: str, part: Path, total_size: int, cancel_ev: threading.Event,
task_id: str, progress_label: str) -> tuple[int, int]:
"""把响应体流式写入 part,返回 (已写字节数, 期望总大小)。
期望总大小取入参,缺失时回落到 Content-Length(仍可能为 0,表示上游没给)。
"""
done = 0
last_update = 0.0
with _stream_open(url, timeout=60) as r:
if r.status >= 400:
raise DownloadException(f"上游返回 {r.status}")
total = total_size or int(r.headers.get('Content-Length') or 0)
resp = await _http.open('GET', url, headers=_STREAM_HEADERS, timeout=60)
try:
if resp.status >= 400:
raise DownloadException(f"上游返回 {resp.status}")
total = total_size or int(resp.headers.get('Content-Length') or 0)
with open(part, 'wb') as f:
for chunk in r.iter_content(chunk_size=256 * 1024):
async for chunk in iter_chunks(resp, 256 * 1024):
if cancel_ev.is_set():
raise DownloadCanceled("任务已取消")
if not chunk:
@@ -116,13 +128,15 @@ def _stream_to_part(url: str, part: Path, total_size: int, cancel_ev: threading.
if now - last_update > 0.5:
last_update = now
_report_progress(task_id, progress_label, done, total)
finally:
resp.close()
return done, total
def _verify_downloaded(target: Path, done: int, total_size: int) -> None:
"""完整性校验:不达标则删掉已落地的文件并抛 DownloadException。
为什么非要校验:CDN 提前断流时 iter_content 会「正常」结束,文件静默截断。
为什么非要校验:CDN 提前断流时流式读取会「正常」结束,文件静默截断。
已知期望大小时要求**精确相等**(API 报的大小与实际一致;放宽到 95% 容差会
交付截断的坏文件还照扣次数);期望未知时退化为非空校验——Content-Length
兜底值可能是压缩口径,不做精确比对。
@@ -135,21 +149,21 @@ def _verify_downloaded(target: Path, done: int, total_size: int) -> None:
raise DownloadException("下载内容为空,请重试")
def _podcast_stream_download(url: str, target: Path, total_size: int,
cancel_ev: threading.Event,
task_id: str = '', progress_label: str = '') -> int:
async def _podcast_stream_download(url: str, target: Path, total_size: int,
cancel_ev: threading.Event,
task_id: str = '', progress_label: str = '') -> int:
"""流式下载播客音频到 target(先写 .part 再改名),返回实际字节数。
自动加入全局下载信号量排队;每 0.5s 更新一次任务进度消息。
自动加入全局下载闸排队;每 0.5s 更新一次任务进度消息。
取消时 .part 会留存(不删)——下次下载同名文件直接覆盖,是既有行为。
"""
part = target.with_name(target.name + '.part')
# 等待全局下载名额期间可被取消(与音乐批量 BATCH_ZIP_SEM 同语义)
sem = api_service.downloader._download_semaphore
if not sem.acquire_cancellable(cancel_ev):
if not await sem.acquire_cancellable(cancel_ev):
raise DownloadCanceled("任务已取消")
try:
done, _total = _stream_to_part(url, part, total_size, cancel_ev, task_id, progress_label)
done, _total = await _stream_to_part(url, part, total_size, cancel_ev, task_id, progress_label)
finally:
sem.release()
if part.exists():
@@ -158,13 +172,13 @@ def _podcast_stream_download(url: str, target: Path, total_size: int,
return done
def _podcast_resolve_audio(program: dict[str, Any], quality: str,
cookies: dict[str, str]) -> dict[str, Any]:
async def _podcast_resolve_audio(program: dict[str, Any], quality: str,
cookies: dict[str, str]) -> dict[str, Any]:
"""解析单集音频直链,失败抛 DownloadException"""
song_id = program.get('main_song_id')
if not song_id:
raise DownloadException("该单集缺少音频信息(mainSong)")
url_info = podcast.resolve_episode_url(song_id, cookies, quality)
url_info = await podcast.resolve_episode_url(song_id, cookies, quality)
if not url_info or not url_info.get('url'):
raise DownloadException("未获取到音频直链(单集可能已下架或受版权限制)")
return url_info
@@ -242,21 +256,16 @@ def _prepare_podcast_target(task_id: str, program_id: Any, program: dict[str, An
def _write_podcast_zip(zip_path: str, file_path_str: str, arcname: str, base: str,
name: str, program: dict[str, Any], url_info: dict[str, Any],
fallback_quality: str) -> None:
fallback_quality: str, cover: bytes = b'') -> None:
"""单集入包:音频 + 封面(可选,失败不炸任务)+ info.txt。
info.txt 不再写直链(真实 URL 不应随交付文件外泄)。
封面字节由调用方先取好(网络等待留在协程里),本函数只做阻塞的落盘组装。
"""
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
zf.write(file_path_str, arcname=arcname)
cover_url = program.get('cover_url') or ''
if cover_url:
try:
cover = fetch_cover_bytes(cover_url)
if cover:
zf.writestr(f"{base}.jpg", cover)
except Exception:
pass
if cover:
zf.writestr(f"{base}.jpg", cover)
info_txt = (
f"单集: {name}\n"
f"播客: {program.get('radio_name') or ''}\n"
@@ -277,16 +286,24 @@ def _podcast_file_result(file_path_str: str, filename: str, ext: str) -> dict[st
}
def _podcast_zip_result(prep: _PodcastTarget, file_path_str: str,
program: dict[str, Any], url_info: dict[str, Any],
spec: _PodcastTaskSpec) -> dict[str, Any]:
async def _podcast_zip_result(prep: _PodcastTarget, file_path_str: str,
program: dict[str, Any], url_info: dict[str, Any],
spec: _PodcastTaskSpec) -> dict[str, Any]:
"""打包交付形状:ZIP 中间文件建在任务目录下(失败收尾 rmtree 一并覆盖)。"""
cover: bytes = b''
cover_url = program.get('cover_url') or ''
if cover_url:
try:
cover = await fetch_cover_bytes(cover_url) or b''
except Exception:
cover = b''
fd, zip_tmp_path = tempfile.mkstemp(prefix='podcast_zip_', suffix='.zip',
dir=str(prep.task_dir))
os.close(fd)
_write_podcast_zip(zip_tmp_path, file_path_str, arcname=prep.filename,
base=prep.base, name=prep.name, program=program,
url_info=url_info, fallback_quality=spec.quality)
await asyncio.to_thread(_write_podcast_zip, zip_tmp_path, file_path_str,
arcname=prep.filename, base=prep.base, name=prep.name,
program=program, url_info=url_info,
fallback_quality=spec.quality, cover=cover)
return {
'file_path': file_path_str,
'zip_path': zip_tmp_path,
@@ -296,8 +313,8 @@ def _podcast_zip_result(prep: _PodcastTarget, file_path_str: str,
}
def _publish_podcast_task(task_id: str, result: dict[str, Any], remote_ip: str,
name: str, filename: str) -> None:
async def _publish_podcast_task(task_id: str, result: dict[str, Any], remote_ip: str,
name: str, filename: str) -> None:
"""最终发布:置 done(已终态不覆盖)→ 结算 → 记操作日志。
交付已落定;结算失败**不再**把任务改标 error——钱由重启对账兜底,
@@ -313,7 +330,7 @@ def _publish_podcast_task(task_id: str, result: dict[str, Any], remote_ip: str,
t['msg'] = '下载完成'
t['result'] = result
try:
auth_system.ledger_settle(task_id, 1, 'delivered')
await asyncio.to_thread(auth_system.ledger_settle, task_id, 1, 'delivered')
except Exception as _e:
api_service.logger.error(f"播客单集交付结算失败(重启对账兜底): {task_id} {_e}")
try:
@@ -323,19 +340,19 @@ def _publish_podcast_task(task_id: str, result: dict[str, Any], remote_ip: str,
api_service.logger.info(f"播客单集下载完成: {filename} ({task_id})")
def _fail_podcast_task(task_id: str, status: str, msg: str, ledger_status: str,
task_dir: Path | None) -> None:
async def _fail_podcast_task(task_id: str, status: str, msg: str, ledger_status: str,
task_dir: Path | None) -> None:
"""失败/取消的统一收尾:置终态 → 退款 → 清掉任务目录(含 ZIP 中间件)。"""
_mark_task_terminal(task_id, status, msg)
await _mark_task_terminal(task_id, status, msg)
try:
auth_system.ledger_settle(task_id, 0, ledger_status)
await asyncio.to_thread(auth_system.ledger_settle, task_id, 0, ledger_status)
except Exception:
pass
if task_dir is not None:
shutil.rmtree(str(task_dir), ignore_errors=True)
await asyncio.to_thread(shutil.rmtree, str(task_dir), ignore_errors=True)
def _podcast_download_worker(task_id: str) -> None:
async def _podcast_download_worker(task_id: str) -> None:
"""后台播客单集下载:解析单集 → 音质降级取直链 → 流式下载(可选 ZIP 打包)
任务 type 为 'single',完成后经 /download/result 交付,与单曲下载共用交付通道。
@@ -344,37 +361,37 @@ def _podcast_download_worker(task_id: str) -> None:
task_dir: Path | None = None
try:
spec = _begin_podcast_task(task_id)
program = podcast.get_program_detail(spec.program_id, spec.cookies)
url_info = _podcast_resolve_audio(program, spec.quality, spec.cookies)
program = await podcast.get_program_detail(spec.program_id, spec.cookies)
url_info = await _podcast_resolve_audio(program, spec.quality, spec.cookies)
prep = _prepare_podcast_target(task_id, spec.program_id, program, url_info)
task_dir = prep.task_dir
with DOWNLOAD_TASKS_LOCK:
t = DOWNLOAD_TASKS[task_id]
t['msg'] = '下载中...'
_podcast_stream_download(url_info['url'], prep.target, url_info.get('size', 0),
spec.cancel_ev, task_id, '下载中')
await _podcast_stream_download(url_info['url'], prep.target, url_info.get('size', 0),
spec.cancel_ev, task_id, '下载中')
_abort_if_canceled(spec.cancel_ev)
file_path_str = str(prep.target)
if spec.need_zip:
result = _podcast_zip_result(prep, file_path_str, program, url_info, spec)
result = await _podcast_zip_result(prep, file_path_str, program, url_info, spec)
else:
result = _podcast_file_result(file_path_str, prep.filename, prep.ext)
# 打包阶段同样以取消检查收口(末段取消不得覆盖为 done)
_abort_if_canceled(spec.cancel_ev)
_publish_podcast_task(task_id, result, spec.remote_ip, prep.name, prep.filename)
await _publish_podcast_task(task_id, result, spec.remote_ip, prep.name, prep.filename)
except DownloadCanceled:
api_service.logger.info(f"播客单集下载已取消: {task_id}")
_fail_podcast_task(task_id, 'canceled', '任务已取消', 'canceled', task_dir)
await _fail_podcast_task(task_id, 'canceled', '任务已取消', 'canceled', task_dir)
except DownloadException as e:
api_service.logger.error(f"播客单集下载失败: {task_id} {e}")
_fail_podcast_task(task_id, 'error', str(e), 'error', task_dir)
await _fail_podcast_task(task_id, 'error', str(e), 'error', task_dir)
except Exception as e:
# 非预期异常原文 logger 先行,用户可见文案泛化(教训)
api_service.logger.error(f"播客单集下载异常: {task_id} {e}\n{traceback.format_exc()}")
_fail_podcast_task(task_id, 'error', '下载失败,请稍后重试', 'error', task_dir)
await _fail_podcast_task(task_id, 'error', '下载失败,请稍后重试', 'error', task_dir)
def _podcast_cleanup_files(paths: list[str | None]) -> None:
@@ -397,7 +414,7 @@ def _podcast_cleanup_files(paths: list[str | None]) -> None:
@dataclass(frozen=True)
class _EpisodePayload:
"""一集下载完成后的入包素材(下载线程产出,落包线程消费)。"""
"""一集下载完成后的入包素材(下载协程产出,落包协程消费)。"""
path: str
base: str
@@ -409,7 +426,7 @@ class _PodcastZipJob(ZipJob):
并发刻意等于音乐批量:同样占用全局批量名额(BATCH_ZIP_SEM,全局 3),
逐集 acquire/release——暂停等待/取消时不长期占名额;音频本身仍受全局
下载信号量约束。原实现不受批量并发控制,多用户同时打包会无限并发。
下载闸约束。原实现不受批量并发控制,多用户同时打包会无限并发。
"""
tag = '播客打包'
@@ -422,20 +439,20 @@ class _PodcastZipJob(ZipJob):
def __init__(self) -> None:
self._radio_name = ''
def prepare(self, params: dict[str, Any], task_id: str, failed: list[str]) -> list[Any]:
async def prepare(self, params: dict[str, Any], task_id: str, failed: list[str]) -> list[Any]:
cookies = params['cookies']
radio_id = params['radio_id']
limit = params['limit']
# 组装单集清单:整台电台(正序全量)或指定单集ID列表
if radio_id:
episodes = podcast.list_radio_all_program_ids(radio_id, cookies, max_count=limit)
episodes = await podcast.list_radio_all_program_ids(radio_id, cookies, max_count=limit)
if not episodes:
raise DownloadException("该电台暂无可下载的单集")
else:
episodes = []
for pid in (params.get('ids') or []):
try:
prog = podcast.get_program_detail(pid, cookies)
prog = await podcast.get_program_detail(pid, cookies)
episodes.append({
'id': prog['id'],
'name': prog['name'],
@@ -453,7 +470,7 @@ class _PodcastZipJob(ZipJob):
self._radio_name = _podcast_safe_name(params.get('radio_name') or '', '播客')
return episodes
def supplement(self, task_id: str, params: dict[str, Any], count: int) -> None:
async def supplement(self, task_id: str, params: dict[str, Any], count: int) -> None:
"""按次计费补扣:整台电台提交时只预扣 1 次,此处按实际单集数补足差额。
补扣失败(余额不足/数据库异常)任务必须失败并按账本退费——不允许无账本继续交付。
@@ -462,7 +479,7 @@ class _PodcastZipJob(ZipJob):
_buid = params.get('billing_uid')
_extra = count - int(params.get('billed') or 1)
if _buid and _extra > 0:
if not auth_system.ledger_supplement(task_id, _extra):
if not await asyncio.to_thread(auth_system.ledger_supplement, task_id, _extra):
raise DownloadException(
f"补扣下载次数失败(需补扣 {_extra} 次),任务已取消,预扣部分将退回")
if _buid:
@@ -476,13 +493,13 @@ class _PodcastZipJob(ZipJob):
except Exception as e:
raise DownloadException(f"补扣下载次数异常: {e}") from e
def download_one(self, item: Any, idx: int, ctx: ZipContext) -> _EpisodePayload:
async def download_one(self, item: Any, idx: int, ctx: ZipContext) -> _EpisodePayload:
ep = item
label = f"[{idx}/{ctx.total}] {ep['name'][:24]}"
ctx.progress(f"{label} 解析中...")
cookies = ctx.params['cookies']
prog = ep.get('detail') or podcast.get_program_detail(ep['id'], cookies)
url_info = _podcast_resolve_audio(prog, ctx.params['quality'], cookies)
prog = ep.get('detail') or await podcast.get_program_detail(ep['id'], cookies)
url_info = await _podcast_resolve_audio(prog, ctx.params['quality'], cookies)
ctx.progress(f"{label} 下载中...")
ext = (url_info.get('type') or 'mp3').lower().lstrip('.')
serial = int(ep.get('serial_num') or 0)
@@ -492,15 +509,15 @@ class _PodcastZipJob(ZipJob):
# 单集(Linux 上 unlink 打开中的文件)
tmp_audio = ctx.work_dir / f"podcast_zip_tmp_{ctx.task_id}_{idx}.{ext}"
try:
_podcast_stream_download(url_info['url'], tmp_audio,
url_info.get('size', 0), ctx.cancel_ev)
await _podcast_stream_download(url_info['url'], tmp_audio,
url_info.get('size', 0), ctx.cancel_ev)
except Exception:
# 下载失败即清(.part 残片同清);成功时由 write_entry 的 finally 清
_podcast_cleanup_files([str(tmp_audio)])
raise
return _EpisodePayload(path=str(tmp_audio), base=base, ext=ext)
def write_entry(self, item: Any, idx: int, payload: _EpisodePayload, ctx: ZipContext) -> None:
async def write_entry(self, item: Any, idx: int, payload: _EpisodePayload, ctx: ZipContext) -> None:
ep = item
try:
# 重名条目自动追加序号(同名单集/同号不同集不得互相覆盖)
@@ -510,11 +527,12 @@ class _PodcastZipJob(ZipJob):
arcname = f"{payload.base} ({k}).{payload.ext}"
k += 1
ctx.used_arcnames.add(arcname)
ctx.zf.write(payload.path, arcname=arcname, compress_type=zipfile.ZIP_STORED)
await asyncio.to_thread(ctx.zf.write, payload.path, arcname=arcname,
compress_type=zipfile.ZIP_STORED)
# 首集附带封面,便于识别
if idx == 1 and ep.get('cover_url'):
try:
cover = fetch_cover_bytes(ep['cover_url'])
cover = await fetch_cover_bytes(ep['cover_url'])
if cover:
ctx.zf.writestr("cover.jpg", cover, compress_type=zipfile.ZIP_STORED)
except Exception:
@@ -541,7 +559,7 @@ class _PodcastZipJob(ZipJob):
return f"全部单集下载失败: {'; '.join(failed[:3])}" + (
f"(已退回 {refunded} 次下载次数)" if refunded else '')
def on_delivered(self, items: list[Any], task_id: str, params: dict[str, Any]) -> None:
async def on_delivered(self, items: list[Any], task_id: str, params: dict[str, Any]) -> None:
try:
first_name = items[0].get('name') if items else ''
_record_log('下载', params.get('remote_ip') or '-',
@@ -550,6 +568,6 @@ class _PodcastZipJob(ZipJob):
pass
def _podcast_zip_worker(task_id: str) -> None:
async def _podcast_zip_worker(task_id: str) -> None:
"""整台播客打包:逐集 下载→入包即删,支持取消与断线暂停(复用批量任务机制)"""
run_zip_job(_PodcastZipJob(), task_id, settle=_settle_batch_billing)
await run_zip_job(_PodcastZipJob(), task_id, settle=_settle_batch_billing)