Archived
拆掉「同步调异步 / 异步桥同步」两类垫片的第二半(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 自用)。
180 lines
6.1 KiB
Python
180 lines
6.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""aria2 下载后端的单元测试(用假 api 驱动,不需要真实 aria2c 二进制)。
|
|
|
|
覆盖:
|
|
- aria2c 缺失时 get_backend 静默降级且失败结果被记忆
|
|
- 正常完成路径的进度回调与自动清理
|
|
- 取消 / 体积超限 连带删除残片;任务失败 / 总超时 保留残片供续传
|
|
- 提交失败与 RPC 抖动统一上报为可重试异常
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
|
|
import pytest
|
|
|
|
import music_downloader._aria2 as a2
|
|
from core.http_client import UpstreamNetworkError
|
|
from music_downloader import DownloadCanceled, DownloadException
|
|
|
|
|
|
class _FakeDownload:
|
|
"""按预设步进产出状态,模拟 aria2 的 tellStatus 轮询。"""
|
|
|
|
def __init__(self, steps):
|
|
self.gid = 'g1'
|
|
self._steps = list(steps)
|
|
self._i = 0
|
|
self.completed_length = 0
|
|
self.total_length = 100
|
|
self.is_complete = False
|
|
self.has_failed = False
|
|
self.error_message = ''
|
|
self.status = 'active'
|
|
|
|
def update(self):
|
|
idx = min(self._i, len(self._steps) - 1)
|
|
done, complete, failed = self._steps[idx]
|
|
self._i += 1
|
|
self.completed_length = done
|
|
self.is_complete = complete
|
|
self.has_failed = failed
|
|
if failed:
|
|
self.status = 'error'
|
|
self.error_message = 'boom'
|
|
|
|
|
|
class _FakeAPI:
|
|
def __init__(self, download, fail_submit=False, fail_update=False):
|
|
self.download = download
|
|
self.removed: list[tuple[str, bool, bool]] = []
|
|
self.submitted: tuple[list[str], dict[str, str]] | None = None
|
|
self._fail_submit = fail_submit
|
|
self._fail_update = fail_update
|
|
|
|
def add_uris(self, uris, options=None):
|
|
if self._fail_submit:
|
|
raise RuntimeError('rpc down')
|
|
self.submitted = (list(uris), options or {})
|
|
return self.download
|
|
|
|
def remove(self, downloads, force=False, files=False):
|
|
self.removed.append((downloads[0].gid, force, files))
|
|
|
|
|
|
class _FailUpdateDownload(_FakeDownload):
|
|
def update(self):
|
|
raise RuntimeError('rpc jitter')
|
|
|
|
|
|
class _FakeProc:
|
|
def poll(self):
|
|
return 0
|
|
|
|
def terminate(self):
|
|
pass
|
|
|
|
def kill(self):
|
|
pass
|
|
|
|
def wait(self, timeout=None):
|
|
return 0
|
|
|
|
|
|
def _backend(monkeypatch, steps, **kw):
|
|
# fetch 的轮询改 asyncio.sleep(不再 time.sleep):把间隔压到 0 让状态机快速走完
|
|
monkeypatch.setattr(a2, '_POLL_INTERVAL', 0.0)
|
|
dl = _FailUpdateDownload([]) if kw.get('fail_update') else _FakeDownload(steps)
|
|
api = _FakeAPI(dl, fail_submit=kw.get('fail_submit', False))
|
|
return a2.Aria2Backend(api, _FakeProc(), 6800), api
|
|
|
|
|
|
# ---------- 降级 ----------
|
|
|
|
def test_get_backend_degrades_without_binary(monkeypatch):
|
|
monkeypatch.setattr(a2.shutil, 'which', lambda _n: None)
|
|
monkeypatch.setattr(a2, '_backend', None)
|
|
monkeypatch.setattr(a2, '_unavailable', False)
|
|
assert a2.get_backend() is None
|
|
assert a2.get_backend() is None # 失败结果被记忆,不反复拉起进程
|
|
|
|
|
|
def test_free_port_is_in_valid_range():
|
|
assert 0 < a2._free_port() < 65536
|
|
|
|
|
|
# ---------- 完成路径 ----------
|
|
|
|
async def test_fetch_reports_progress_and_completes(monkeypatch, tmp_path):
|
|
be, api = _backend(monkeypatch, [(50, False, False), (100, True, False)])
|
|
seen = []
|
|
await be.fetch('http://x/y.mp3', tmp_path / 'y.part',
|
|
progress_cb=lambda done, total: seen.append((done, total)))
|
|
assert seen == [(50, 100), (100, 100)]
|
|
assert api.removed == [] # 完成不需要中止
|
|
assert not (tmp_path / 'y.part.aria2').exists() # 控制文件已兜底清理
|
|
submitted = api.submitted
|
|
assert submitted is not None
|
|
options = submitted[1]
|
|
assert options['continue'] == 'true' # 续传选项已下发
|
|
assert options['max-connection-per-server'] == str(a2._SPLIT)
|
|
|
|
|
|
async def test_progress_callback_exception_is_swallowed(monkeypatch, tmp_path):
|
|
be, _api = _backend(monkeypatch, [(100, True, False)])
|
|
|
|
def boom(_d, _t):
|
|
raise RuntimeError('cb')
|
|
|
|
await be.fetch('http://x/y.mp3', tmp_path / 'y.part', progress_cb=boom) # 不应抛出
|
|
|
|
|
|
# ---------- 取消 / 守卫 / 失败 ----------
|
|
|
|
async def test_fetch_maps_cancel_and_drops_partial(monkeypatch, tmp_path):
|
|
be, api = _backend(monkeypatch, [(10, False, False)])
|
|
ev = threading.Event()
|
|
ev.set()
|
|
with pytest.raises(DownloadCanceled):
|
|
await be.fetch('http://x/y.mp3', tmp_path / 'y.part', cancel_event=ev)
|
|
assert api.removed == [('g1', True, True)]
|
|
|
|
|
|
async def test_fetch_guards_size_and_drops_partial(monkeypatch, tmp_path):
|
|
be, api = _backend(monkeypatch, [(700, False, False)])
|
|
with pytest.raises(DownloadException):
|
|
await be.fetch('http://x/y.mp3', tmp_path / 'y.part', max_bytes=500)
|
|
assert api.removed == [('g1', True, True)]
|
|
|
|
|
|
async def test_fetch_failure_is_retryable_and_keeps_partial(monkeypatch, tmp_path):
|
|
be, api = _backend(monkeypatch, [(10, False, True)])
|
|
with pytest.raises(UpstreamNetworkError):
|
|
await be.fetch('http://x/y.mp3', tmp_path / 'y.part')
|
|
assert api.removed == [] # 残片保留,供下轮续传
|
|
|
|
|
|
async def test_fetch_timeout_is_retryable(monkeypatch, tmp_path):
|
|
be, api = _backend(monkeypatch, [(10, False, False)]) # 永不完成
|
|
with pytest.raises(UpstreamNetworkError):
|
|
await be.fetch('http://x/y.mp3', tmp_path / 'y.part', timeout=-1)
|
|
assert api.removed == [('g1', True, False)] # 超时中止但保留残片
|
|
|
|
|
|
async def test_fetch_submit_failure_is_retryable(monkeypatch, tmp_path):
|
|
be, _api = _backend(monkeypatch, [], fail_submit=True)
|
|
with pytest.raises(UpstreamNetworkError):
|
|
await be.fetch('http://x/y.mp3', tmp_path / 'y.part')
|
|
|
|
|
|
async def test_fetch_update_failure_is_retryable(monkeypatch, tmp_path):
|
|
be, _api = _backend(monkeypatch, [], fail_update=True)
|
|
with pytest.raises(UpstreamNetworkError):
|
|
await be.fetch('http://x/y.mp3', tmp_path / 'y.part')
|
|
|
|
|
|
def test_close_is_idempotent(monkeypatch):
|
|
be, _api = _backend(monkeypatch, [])
|
|
be.close()
|
|
be.close()
|