Archived
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:
1 parent
65adfc9089
commit
69a50c2c31
35 files changed
+1062
-1005
No files matched your search
+31
-19
@@ -16,6 +16,7 @@ ZIP 内容、账本守恒、暂停/恢复/取消语义。断言只依赖「调
|
||||
账本口径:一律用 ``reserve_and_open`` 真预扣(``ledger_open`` 只记账不扣款,
|
||||
会让「退款」凭空给余额加次数,守恒断言就失去意义)。
|
||||
"""
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
@@ -59,7 +60,7 @@ class _FakeDownloader:
|
||||
self.calls: list[int] = []
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def get_music_info(self, mid: Any, quality: str, cookies: Any) -> MusicInfo:
|
||||
async def get_music_info(self, mid: Any, quality: str, cookies: Any) -> MusicInfo:
|
||||
return MusicInfo(
|
||||
id=int(mid), name=f'歌{mid}', artists='歌手A', album='专辑A',
|
||||
pic_url='', duration=200, track_number=1, download_url='',
|
||||
@@ -67,7 +68,7 @@ class _FakeDownloader:
|
||||
lyric='[00:01.00]第一行\n[00:02.00]第二行',
|
||||
)
|
||||
|
||||
def download_music_file(self, mid: Any, quality: str, **kw: Any) -> DownloadResult:
|
||||
async def download_music_file(self, mid: Any, quality: str, **kw: Any) -> DownloadResult:
|
||||
with self._lock:
|
||||
self.calls.append(int(mid))
|
||||
seq = len(self.calls)
|
||||
@@ -199,7 +200,11 @@ def _register_podcast(sandbox, pids: list[int], *, reserved: int, user_id: int)
|
||||
|
||||
|
||||
def _run(worker, task_id: str) -> threading.Thread:
|
||||
th = threading.Thread(target=worker, args=(task_id,), daemon=True)
|
||||
"""把 worker 协程跑在独立线程的私有事件循环里(等价于生产的任务循环)。"""
|
||||
def _target() -> None:
|
||||
asyncio.run(worker(task_id))
|
||||
|
||||
th = threading.Thread(target=_target, daemon=True)
|
||||
th.start()
|
||||
return th
|
||||
|
||||
@@ -346,8 +351,9 @@ def test_batch_zip_cancel_at_publish_checkpoint_delivers(sandbox, monkeypatch):
|
||||
holder: dict[str, Any] = {}
|
||||
real_settle = batch_svc._settle_batch_billing
|
||||
|
||||
def settle_then_cancel(task_id: str, ok_count: int, final_status: str = 'settled') -> int:
|
||||
refunded = real_settle(task_id, ok_count, final_status)
|
||||
async def settle_then_cancel(task_id: str, ok_count: int,
|
||||
final_status: str = 'settled') -> int:
|
||||
refunded = await real_settle(task_id, ok_count, final_status)
|
||||
holder['task']['cancel'].set() # 结算已完成、发布前一刻取消
|
||||
return refunded
|
||||
|
||||
@@ -371,24 +377,27 @@ def test_batch_zip_cancel_at_publish_checkpoint_delivers(sandbox, monkeypatch):
|
||||
@pytest.fixture()
|
||||
def podcast_stub(monkeypatch, sandbox):
|
||||
"""把播客上游与流式下载替换为本地确定性实现。"""
|
||||
def fake_detail(pid: Any, cookies: Any) -> dict[str, Any]:
|
||||
async def fake_detail(pid: Any, cookies: Any) -> dict[str, Any]:
|
||||
n = int(pid)
|
||||
return {'id': n, 'name': f'单集{n}', 'main_song_id': 1,
|
||||
'serial_num': n, 'cover_url': '', 'songs': []}
|
||||
|
||||
def fake_resolve(prog: dict[str, Any], quality: str, cookies: Any) -> dict[str, Any]:
|
||||
async def fake_resolve(prog: dict[str, Any], quality: str, cookies: Any) -> dict[str, Any]:
|
||||
return {'url': f"http://example.invalid/{prog['id']}.mp3", 'size': 2048, 'type': 'mp3'}
|
||||
|
||||
def fake_stream(url: str, target: Path, total_size: int, cancel_ev: Any,
|
||||
task_id: str = '', progress_label: str = '') -> int:
|
||||
async def fake_stream(url: str, target: Path, total_size: int, cancel_ev: Any,
|
||||
task_id: str = '', progress_label: str = '') -> int:
|
||||
if cancel_ev is not None and cancel_ev.is_set():
|
||||
raise DownloadCanceled('任务已取消')
|
||||
target.write_bytes(b'\xff\xfb\x90\x00' + b'\x00' * 128)
|
||||
return target.stat().st_size
|
||||
|
||||
async def _no_cover(_u: str) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(podcast_svc, '_podcast_resolve_audio', fake_resolve)
|
||||
monkeypatch.setattr(podcast_svc, '_podcast_stream_download', fake_stream)
|
||||
monkeypatch.setattr(podcast_svc, 'fetch_cover_bytes', lambda _u: None)
|
||||
monkeypatch.setattr(podcast_svc, 'fetch_cover_bytes', _no_cover)
|
||||
monkeypatch.setattr(podcast_svc.podcast, 'get_program_detail', fake_detail)
|
||||
return sandbox
|
||||
|
||||
@@ -418,7 +427,7 @@ def test_podcast_zip_pause_then_resume(podcast_stub, monkeypatch):
|
||||
holder: dict[str, Any] = {}
|
||||
fired = {'n': 0}
|
||||
|
||||
def _pause_once(url, target, total_size, cancel_ev, task_id='', progress_label=''):
|
||||
async def _pause_once(url, target, total_size, cancel_ev, task_id='', progress_label=''):
|
||||
target.write_bytes(b'\xff\xfb\x90\x00' + b'\x00' * 128)
|
||||
fired['n'] += 1
|
||||
if fired['n'] == 1: # 只在第一集触发——否则恢复后立刻又被暂停
|
||||
@@ -447,7 +456,7 @@ def test_podcast_zip_all_fail_refunds(podcast_stub, monkeypatch):
|
||||
uid = _uid()
|
||||
before = _balance()
|
||||
|
||||
def _boom(prog, quality, cookies):
|
||||
async def _boom(prog, quality, cookies):
|
||||
raise RuntimeError('上游不可用')
|
||||
|
||||
monkeypatch.setattr(podcast_svc, '_podcast_resolve_audio', _boom)
|
||||
@@ -470,9 +479,9 @@ def test_podcast_zip_all_fail_refunds(podcast_stub, monkeypatch):
|
||||
class _SameNameDownloader(_FakeDownloader):
|
||||
"""所有歌曲同名同歌手、且都带封面——用于验证包内三条目共享序号后缀。"""
|
||||
|
||||
def get_music_info(self, mid: Any, quality: str, cookies: Any) -> MusicInfo:
|
||||
return replace(super().get_music_info(mid, quality, cookies),
|
||||
name='同名歌', artists='同歌手',
|
||||
async def get_music_info(self, mid: Any, quality: str, cookies: Any) -> MusicInfo:
|
||||
base = await super().get_music_info(mid, quality, cookies)
|
||||
return replace(base, name='同名歌', artists='同歌手',
|
||||
pic_url='http://example.invalid/cover.jpg')
|
||||
|
||||
|
||||
@@ -485,7 +494,10 @@ def test_batch_zip_dedups_three_arcnames_with_shared_suffix(sandbox, monkeypatch
|
||||
"""
|
||||
uid = _uid()
|
||||
monkeypatch.setattr(api_service, 'downloader', _SameNameDownloader(sandbox['cache']))
|
||||
monkeypatch.setattr(batch_svc, 'fetch_cover_bytes', lambda _u: b'\xff\xd8\xff\xe0')
|
||||
async def _cover(_u: str) -> bytes:
|
||||
return b'\xff\xd8\xff\xe0'
|
||||
|
||||
monkeypatch.setattr(batch_svc, 'fetch_cover_bytes', _cover)
|
||||
tid, task = _register_batch(sandbox, [701, 702], reserved=2, user_id=uid)
|
||||
|
||||
th = _run(batch_svc._batch_zip_worker, tid)
|
||||
@@ -528,7 +540,7 @@ def test_podcast_all_fail_message_and_ledger_status(podcast_stub, monkeypatch):
|
||||
uid = _uid()
|
||||
before = _balance()
|
||||
|
||||
def _boom(prog, quality, cookies):
|
||||
async def _boom(prog, quality, cookies):
|
||||
raise RuntimeError('上游不可用')
|
||||
|
||||
monkeypatch.setattr(podcast_svc, '_podcast_resolve_audio', _boom)
|
||||
@@ -557,8 +569,8 @@ def test_podcast_cleans_temp_files_on_episode_failure(podcast_stub, monkeypatch)
|
||||
uid = _uid()
|
||||
before = _balance()
|
||||
|
||||
def _flaky(url: str, target: Path, total_size: int, cancel_ev: Any,
|
||||
task_id: str = '', progress_label: str = '') -> int:
|
||||
async def _flaky(url: str, target: Path, total_size: int, cancel_ev: Any,
|
||||
task_id: str = '', progress_label: str = '') -> int:
|
||||
if '/102.' in url:
|
||||
target.write_bytes(b'\x00' * 64) # 正文残留
|
||||
target.with_name(target.name + '.part').write_bytes(b'\x00' * 32) # 残片
|
||||
|
||||
Reference in new issue
Block a user