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
@@ -10,8 +10,11 @@
|
||||
- ``downloads``:单曲下载、账号探测与任务交付
|
||||
- ``batch``:歌单/专辑批量打包 worker
|
||||
- ``podcast``:播客单集下载与整台打包 worker
|
||||
- ``streaming``:同步流式响应垫片(音频分段透传)
|
||||
- ``tasks``:任务监控循环、设备心跳与缓存清扫
|
||||
|
||||
worker 与打包引擎都是协程,由 ``_taskcore._start_task`` 作为 asyncio 任务挂到
|
||||
应用事件循环上(不再起线程);监控循环仍是一条常驻线程——它每轮只做周期性的
|
||||
文件/库维护,不参与请求链路,留在线程里既不占事件循环也不额外引入 to_thread。
|
||||
"""
|
||||
|
||||
# ============ 依赖自检 ============
|
||||
|
||||
+56
-25
@@ -1,7 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""任务生命周期原语(启动 / 终态 / 文件收尾 / 结算)。
|
||||
|
||||
worker 自本轮起是协程:``_start_task`` 把 ``worker(*args)`` 包成 asyncio 任务挂到
|
||||
应用事件循环上(原先起一条线程)。任务字典里的句柄随之由 ``worker_thread`` 换成
|
||||
``worker_task``,监控循环对「worker 已结束但没人走终态结算」的兜底判断改为
|
||||
``task.done()``——语义不变(settle 幂等,无双退)。
|
||||
|
||||
取消/暂停位仍是 ``threading.Event``:置位方可能是监控线程或请求线程,读取方是
|
||||
worker 协程,只有"置位"与"轮询读取"两种操作,既不需要跨循环唤醒也不会被事件
|
||||
循环卡住,比 asyncio.Event 更省心。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
@@ -21,20 +31,31 @@ from .api_service import (
|
||||
api_service,
|
||||
)
|
||||
|
||||
# 存活期的后台任务强引用——asyncio 只持弱引用,不留引用的话任务可能中途被 GC
|
||||
_BACKGROUND_TASKS: set[asyncio.Task] = set()
|
||||
|
||||
def _start_task_thread(task_id: str, target, args=()) -> str | None:
|
||||
|
||||
def _log_worker_crash(handle: asyncio.Task) -> None:
|
||||
"""worker 的异常逃逸到任务层时留痕。
|
||||
|
||||
正常情况下 worker 自带四路终态收敛,不会抛到这里;真抛出来说明收尾路径本身
|
||||
出了问题,必须留下 traceback,否则任务永远停在 running 且无人知晓。
|
||||
"""
|
||||
if handle.cancelled():
|
||||
return
|
||||
exc = handle.exception()
|
||||
if exc is not None:
|
||||
api_service.logger.error(f"任务 worker 异常退出: {exc}", exc_info=exc)
|
||||
|
||||
|
||||
def _start_task(task_id: str, worker, args: tuple = ()) -> str | None:
|
||||
"""启动任务 worker(启动失败时收敛任务终态并按账本退费,不留僵尸 queued 记录)。
|
||||
退款只走账本(本处 settle 后装饰器看到账已关,不会重复退)。
|
||||
线程句柄存入任务字典——监控循环对 4h 超时任务若发现 worker 线程已死
|
||||
任务句柄存入任务字典——监控循环对 4h 超时任务若发现 worker 已结束
|
||||
(无法自行走到终态结算),可代为按账本结算退款(settle 幂等,无双退)。"""
|
||||
try:
|
||||
th = threading.Thread(target=target, args=args, daemon=True)
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(task_id)
|
||||
if t is not None:
|
||||
t['worker_thread'] = th
|
||||
th.start()
|
||||
return None
|
||||
loop = asyncio.get_running_loop()
|
||||
handle = loop.create_task(worker(*args), name=f'task:{task_id}')
|
||||
except Exception as e:
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.pop(task_id, None)
|
||||
@@ -43,14 +64,22 @@ def _start_task_thread(task_id: str, target, args=()) -> str | None:
|
||||
auth_system.ledger_settle(task_id, 0, 'submit_failed')
|
||||
except Exception:
|
||||
pass
|
||||
api_service.logger.error(f"任务线程启动失败: {task_id} {e}")
|
||||
api_service.logger.error(f"任务启动失败: {task_id} {e}")
|
||||
return f'任务启动失败:{e}'
|
||||
_BACKGROUND_TASKS.add(handle)
|
||||
handle.add_done_callback(_BACKGROUND_TASKS.discard)
|
||||
handle.add_done_callback(_log_worker_crash)
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(task_id)
|
||||
if t is not None:
|
||||
t['worker_task'] = handle
|
||||
return None
|
||||
|
||||
|
||||
def _mark_task_terminal(task_id: str, status: str, msg: str = '') -> None:
|
||||
async def _mark_task_terminal(task_id: str, status: str, msg: str = '') -> None:
|
||||
"""任务进入终态的统一入口(记录 completed_at,保留期从完成时刻起算,
|
||||
而不是从提交时刻起算)。
|
||||
/F-E:置 error/canceled 终态时若 worker 线程已死(无人再走正常结算),
|
||||
/F-E:置 error/canceled 终态时若 worker 已结束(无人再走正常结算),
|
||||
代为按账本结算退款——ledger_settle 幂等,worker 已自行结算过则此处为 0。
|
||||
终态先到先得——已终态(done/error/canceled)的任务
|
||||
不再被覆盖(堵住 canceled→error 的非法迁移边:取消后解析阶段的自身失败
|
||||
@@ -65,15 +94,15 @@ def _mark_task_terminal(task_id: str, status: str, msg: str = '') -> None:
|
||||
t['msg'] = msg or t.get('msg', '')
|
||||
t['completed_at'] = time.time()
|
||||
if status in ('canceled', 'error'):
|
||||
th = t.get('worker_thread')
|
||||
if th is not None and not th.is_alive():
|
||||
wt = t.get('worker_task')
|
||||
if wt is not None and wt.done():
|
||||
need_settle = True
|
||||
# settle 移到任务锁外——ledger_settle 内部要抢 _DB_LOCK 写库
|
||||
# settle 移到任务锁外——ledger_settle 内部要抢 SQLite 写锁
|
||||
# (busy 最长 15s),持任务锁调用会让全站进度/提交/取消/领取随库停摆;
|
||||
# settle 幂等,锁外调用无双退
|
||||
# settle 幂等,锁外调用无双退。落库是同步阻塞调用,经 to_thread 卸载
|
||||
if need_settle:
|
||||
try:
|
||||
auth_system.ledger_settle(task_id, 0, status)
|
||||
await asyncio.to_thread(auth_system.ledger_settle, task_id, 0, status)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -88,11 +117,12 @@ def _task_files(task: dict[str, Any]) -> list[str]:
|
||||
return files
|
||||
|
||||
|
||||
def _settle_batch_billing(task_id: str, ok_count: int, final_status: str = 'settled') -> int:
|
||||
async def _settle_batch_billing(task_id: str, ok_count: int, final_status: str = 'settled') -> int:
|
||||
"""批量任务结算(走持久账本,按实际预扣-实际交付幂等退款;
|
||||
重复调用/重启后调用都只会退一次)"""
|
||||
try:
|
||||
refund = auth_system.ledger_settle(task_id, ok_count, final_status)
|
||||
refund = await asyncio.to_thread(
|
||||
auth_system.ledger_settle, task_id, ok_count, final_status)
|
||||
except Exception:
|
||||
# 本函数多在异常处理器内被调用——结算再抛错(库忙超时)
|
||||
# 会杀死 worker 收尾路径,跳过终态标记;失败留周期对账兜底(幂等)
|
||||
@@ -104,11 +134,12 @@ def _settle_batch_billing(task_id: str, ok_count: int, final_status: str = 'sett
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(task_id) or {}
|
||||
uid = int(t.get('billing_user_id') or 0)
|
||||
u = auth_system.get_user_by_id(uid) if uid else None
|
||||
u = await asyncio.to_thread(auth_system.get_user_by_id, uid) if uid else None
|
||||
uname = u['username'] if u else 'system'
|
||||
remaining = u['duration_seconds'] if u else '?'
|
||||
auth_system.add_log('success', uname, 'system', '批量退费',
|
||||
f'失败部分 {refund} 次已退回,剩余 {remaining} 次')
|
||||
await asyncio.to_thread(
|
||||
auth_system.add_log, 'success', uname, 'system', '批量退费',
|
||||
f'失败部分 {refund} 次已退回,剩余 {remaining} 次')
|
||||
except Exception:
|
||||
pass
|
||||
return refund
|
||||
@@ -127,8 +158,8 @@ def _task_work_dir(task_id: str) -> Path:
|
||||
return path
|
||||
|
||||
|
||||
def _wait_if_paused(task: dict[str, Any], pause_ev: threading.Event,
|
||||
cancel_ev: threading.Event, done: int) -> None:
|
||||
async def _wait_if_paused(task: dict[str, Any], pause_ev: threading.Event,
|
||||
cancel_ev: threading.Event, done: int) -> None:
|
||||
"""断线暂停闸门:置 paused 态并等待恢复或取消,恢复后回到 running。
|
||||
|
||||
两个打包 worker(音乐歌单 / 播客整台)共用同一套暂停语义——此前各自持有
|
||||
@@ -147,7 +178,7 @@ def _wait_if_paused(task: dict[str, Any], pause_ev: threading.Event,
|
||||
task['done'] = done
|
||||
task['msg'] = '已暂停(重新打开页面自动恢复)'
|
||||
while not cancel_ev.is_set() and (pause_ev.is_set() or task.get('status') == 'paused'):
|
||||
time.sleep(1)
|
||||
await asyncio.sleep(1)
|
||||
if cancel_ev.is_set():
|
||||
raise DownloadCanceled("任务已取消")
|
||||
pause_ev.clear()
|
||||
|
||||
+119
-125
@@ -13,25 +13,25 @@
|
||||
|
||||
术语:下文「条目」指一个下载单元——音乐歌单里是一首歌,播客整台里是一集。
|
||||
|
||||
线程模型(本轮最容易踩坏的地方,改动前请先读):
|
||||
- 下载 I/O 在 ``ThreadPoolExecutor`` 里跑,窗口大小 = ``job.concurrency``;
|
||||
- **ZIP 写入与包内名去重只发生在调用线程**(``as_completed`` 消费结果时),
|
||||
:class:`zipfile.ZipFile` 不是线程安全的,且去重读改写 ``used_arcnames``
|
||||
需要串行——故下载与落包被拆成 ``download_one`` / ``write_entry`` 两个钩子,
|
||||
只有前者进线程池。
|
||||
并发模型(本轮最容易踩坏的地方,改动前请先读):
|
||||
- 一个窗口 = ``job.concurrency`` 个条目,窗口内 ``asyncio.gather`` 并发下载;
|
||||
- **ZIP 写入与包内名去重只在引擎协程里串行发生**(按窗口顺序消费结果)——
|
||||
:class:`zipfile.ZipFile` 不是并发安全的,且去重读改写 ``used_arcnames``
|
||||
需要串行;因此 ``download_one``(并发)与 ``write_entry``(串行)是两个钩子,
|
||||
只有前者进 gather。``write_entry`` 里的重型落盘(几百 MB 的音频条目)
|
||||
由实现方自行经 ``asyncio.to_thread`` 卸载,避免卡住事件循环。
|
||||
|
||||
``run_zip_job`` 的四个终态(成功 / 全失败 / 取消 / 异常)原先各写一段 8~20 行的
|
||||
收尾内联在 try/except 里。此处把「一次运行」的状态收进 :class:`_ZipRun`,
|
||||
四个终态各自成函数——改账本口径或补一种终态时,不必再在 167 行里找落点。
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import zipfile
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -80,7 +80,7 @@ class ZipContext:
|
||||
|
||||
task_id: str
|
||||
params: dict[str, Any]
|
||||
cancel_ev: threading.Event
|
||||
cancel_ev: Any
|
||||
work_dir: Path
|
||||
zf: zipfile.ZipFile
|
||||
progress: Callable[..., None]
|
||||
@@ -106,7 +106,7 @@ class ZipJob:
|
||||
|
||||
子类至少实现 :meth:`prepare` / :meth:`download_one` / :meth:`write_entry` /
|
||||
:meth:`zip_filename`,其余钩子按需覆写。**实例每次运行新建**——下载器信息
|
||||
预取池等运行期状态就挂在实例上。
|
||||
预取任务等运行期状态就挂在实例上。
|
||||
"""
|
||||
|
||||
tag = '批量打包' # 日志前缀
|
||||
@@ -119,7 +119,7 @@ class ZipJob:
|
||||
|
||||
# ---- 必须实现 ----
|
||||
|
||||
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]:
|
||||
"""组装条目清单。可抛 ``DownloadException`` 让任务按业务失败收敛。
|
||||
|
||||
``failed`` 可被直接追加——清单阶段就有条目已知失败(如按 ID 列表时个别
|
||||
@@ -127,8 +127,8 @@ class ZipJob:
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def download_one(self, item: Any, idx: int, ctx: ZipContext) -> Any:
|
||||
"""下载单个条目(**在下载线程池内执行**)。
|
||||
async def download_one(self, item: Any, idx: int, ctx: ZipContext) -> Any:
|
||||
"""下载单个条目(**在窗口内并发执行**)。
|
||||
|
||||
返回的 ``payload`` 会原样交给 :meth:`write_entry`(放临时文件名、
|
||||
已取到的元信息等)。失败请抛异常:``ItemFailed`` 用其自带文案,
|
||||
@@ -136,10 +136,12 @@ class ZipJob:
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def write_entry(self, item: Any, idx: int, payload: Any, ctx: ZipContext) -> None:
|
||||
"""把下载结果写入 ZIP(**在引擎调用线程内执行,天然串行**)。
|
||||
async def write_entry(self, item: Any, idx: int, payload: Any, ctx: ZipContext) -> None:
|
||||
"""把下载结果写入 ZIP(**由引擎按窗口顺序串行调用**)。
|
||||
|
||||
包内名去重在这里做——需要读写 ``ctx.used_arcnames``,必须串行。
|
||||
重型落盘请自行 ``await asyncio.to_thread(...)``:直接在协程里写
|
||||
几百 MB 会把事件循环卡住。
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -149,7 +151,7 @@ class ZipJob:
|
||||
|
||||
# ---- 可选钩子 ----
|
||||
|
||||
def prefetch(self, window: list[Any], ctx: ZipContext) -> None:
|
||||
async def prefetch(self, window: list[Any], ctx: ZipContext) -> None:
|
||||
"""窗口级预热(每窗口一次、提交下载前调用)。默认无操作。"""
|
||||
|
||||
def fail_label(self, item: Any) -> str:
|
||||
@@ -174,14 +176,14 @@ class ZipJob:
|
||||
return f"部分{self.item_noun}已打包完成,可领取" + (
|
||||
f",退回 {refunded} 次" if refunded else '')
|
||||
|
||||
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:
|
||||
"""清单确定后的计费补扣(默认无操作)。"""
|
||||
|
||||
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:
|
||||
"""交付落定后的操作记录(默认无操作)。"""
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""释放运行期资源(如信息预取池)。默认无操作。"""
|
||||
async def cleanup(self) -> None:
|
||||
"""释放运行期资源(如信息预取任务)。默认无操作。"""
|
||||
|
||||
|
||||
def _discard(path: str | None) -> None:
|
||||
@@ -206,12 +208,12 @@ class _ZipRun:
|
||||
|
||||
job: ZipJob
|
||||
task_id: str
|
||||
settle: Callable[[str, int, str], int]
|
||||
settle: Callable[[str, int, str], Awaitable[int]]
|
||||
tally: _Tally = field(default_factory=_Tally)
|
||||
task: dict[str, Any] = field(default_factory=dict)
|
||||
params: dict[str, Any] = field(default_factory=dict)
|
||||
cancel_ev: threading.Event | None = None
|
||||
pause_ev: threading.Event | None = None
|
||||
cancel_ev: Any = None
|
||||
pause_ev: Any = None
|
||||
items: list[Any] = field(default_factory=list)
|
||||
zip_tmp_path: str | None = None
|
||||
zip_valid: bool = False
|
||||
@@ -232,7 +234,7 @@ def _progress_of(run: _ZipRun) -> Callable[..., None]:
|
||||
return _progress
|
||||
|
||||
|
||||
def _start_zip_run(run: _ZipRun) -> None:
|
||||
async def _start_zip_run(run: _ZipRun) -> None:
|
||||
"""置 running、组装清单、写回 total、执行计费补扣。"""
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
task = DOWNLOAD_TASKS[run.task_id]
|
||||
@@ -245,13 +247,13 @@ def _start_zip_run(run: _ZipRun) -> None:
|
||||
# 计耗时只算「下载+打包」这一段(不含排队),故不用 task['start']
|
||||
run.t0 = time.time()
|
||||
|
||||
run.items = run.job.prepare(run.params, run.task_id, run.tally.failed)
|
||||
run.items = await run.job.prepare(run.params, run.task_id, run.tally.failed)
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
DOWNLOAD_TASKS[run.task_id]['total'] = len(run.items)
|
||||
run.job.supplement(run.task_id, run.params, len(run.items))
|
||||
await run.job.supplement(run.task_id, run.params, len(run.items))
|
||||
|
||||
|
||||
def _build_zip_archive(run: _ZipRun) -> None:
|
||||
async def _build_zip_archive(run: _ZipRun) -> None:
|
||||
"""建临时 ZIP 并逐窗口填充。返回时 ``zip_valid`` 才置位。
|
||||
|
||||
ZIP 构建放 downloads 卷(原实现落系统 %TEMP%——500 首无损可达 GB 级,
|
||||
@@ -269,7 +271,7 @@ def _build_zip_archive(run: _ZipRun) -> None:
|
||||
ctx = ZipContext(task_id=run.task_id, params=run.params,
|
||||
cancel_ev=run.cancel_ev, work_dir=work_dir, zf=zf,
|
||||
progress=_progress_of(run), total=len(run.items))
|
||||
_fill_zip(job, run.items, ctx, run.tally, run.task, run.pause_ev)
|
||||
await _fill_zip(job, run.items, ctx, run.tally, run.task, run.pause_ev)
|
||||
# zip_valid 只在 ZIP with 块正常退出(中央目录完整写出)后才置 True。
|
||||
# 此前两个 worker 在这之后还各留了一段 `if not zip_valid:` 失败处理——
|
||||
# 紧跟赋值、中间无任何可改zip_valid的语句,是**不可达**的复审残留,已删。
|
||||
@@ -280,7 +282,7 @@ def _build_zip_archive(run: _ZipRun) -> None:
|
||||
BATCH_DURATIONS.append(time.time() - run.t0)
|
||||
|
||||
|
||||
def _finish_all_failed(run: _ZipRun) -> None:
|
||||
async def _finish_all_failed(run: _ZipRun) -> None:
|
||||
"""全部失败(含清单非空但一条都没成):不发布空 ZIP、不按交付结算,转 error 并全额退费。
|
||||
|
||||
原音乐批量用 ``ok==0 and failed``、播客用早抛 ``DownloadException``——这里
|
||||
@@ -289,8 +291,8 @@ def _finish_all_failed(run: _ZipRun) -> None:
|
||||
job, tally = run.job, run.tally
|
||||
_discard(run.zip_tmp_path)
|
||||
run.zip_tmp_path = None
|
||||
refunded = run.settle(run.task_id, 0, 'error')
|
||||
_mark_task_terminal(run.task_id, 'error', job.all_failed_msg(tally.failed, refunded))
|
||||
refunded = await run.settle(run.task_id, 0, 'error')
|
||||
await _mark_task_terminal(run.task_id, 'error', job.all_failed_msg(tally.failed, refunded))
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(run.task_id)
|
||||
if t is not None:
|
||||
@@ -300,7 +302,7 @@ def _finish_all_failed(run: _ZipRun) -> None:
|
||||
f"{job.tag}全部失败: {run.task_id} 失败{len(tally.failed)} 退回{refunded}次")
|
||||
|
||||
|
||||
def _publish_delivery(run: _ZipRun) -> None:
|
||||
async def _publish_delivery(run: _ZipRun) -> None:
|
||||
"""正常交付:按入包成功数结算,锁内复查取消/终态后发布结果。
|
||||
|
||||
``'settled'`` 是 ``_settle_batch_billing`` 的默认值,此处显式写出,让
|
||||
@@ -308,7 +310,7 @@ def _publish_delivery(run: _ZipRun) -> None:
|
||||
"""
|
||||
job, tally = run.job, run.tally
|
||||
assert run.cancel_ev is not None
|
||||
refunded = run.settle(run.task_id, tally.ok, 'settled')
|
||||
refunded = await run.settle(run.task_id, tally.ok, 'settled')
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(run.task_id)
|
||||
# 发布前锁内复查取消/失效状态——取消请求落在「检查后、拿锁前」的窗口
|
||||
@@ -329,24 +331,24 @@ def _publish_delivery(run: _ZipRun) -> None:
|
||||
'filename': job.zip_filename(tally.ok),
|
||||
'audio_files': [], # 缓存文件不归任务所有,不进入清理清单
|
||||
}
|
||||
job.on_delivered(run.items, run.task_id, run.params)
|
||||
await job.on_delivered(run.items, run.task_id, run.params)
|
||||
api_service.logger.info(
|
||||
f"{job.tag}完成: {job.log_label()}成功{tally.ok} 失败{len(tally.failed)} "
|
||||
f"退回{refunded}次 ({run.task_id})")
|
||||
|
||||
|
||||
def _finish_canceled(run: _ZipRun) -> None:
|
||||
async def _finish_canceled(run: _ZipRun) -> None:
|
||||
"""部分成功后取消——已入包部分照常交付(成果守恒),未完成部分按账本退费。
|
||||
|
||||
ZIP 未正常完成(写坏)时不按 ``ok_count`` 交付——按全额退费收敛。
|
||||
"""
|
||||
job, tally = run.job, run.tally
|
||||
delivered = tally.ok if run.zip_valid else 0
|
||||
refunded = run.settle(run.task_id, delivered, 'canceled')
|
||||
refunded = await run.settle(run.task_id, delivered, 'canceled')
|
||||
if delivered > 0 and run.zip_tmp_path:
|
||||
_mark_task_terminal(run.task_id, 'canceled',
|
||||
f"已取消(已打包 {tally.ok} {job.noun}可领取)" +
|
||||
(f",退回 {refunded} 次" if refunded else ''))
|
||||
await _mark_task_terminal(run.task_id, 'canceled',
|
||||
f"已取消(已打包 {tally.ok} {job.noun}可领取)" +
|
||||
(f",退回 {refunded} 次" if refunded else ''))
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(run.task_id)
|
||||
if t is not None:
|
||||
@@ -358,9 +360,9 @@ def _finish_canceled(run: _ZipRun) -> None:
|
||||
}
|
||||
else:
|
||||
_discard(run.zip_tmp_path)
|
||||
_mark_task_terminal(run.task_id, 'canceled',
|
||||
'任务已取消' + (
|
||||
f"(已退回 {refunded} 次下载次数)" if refunded else ''))
|
||||
await _mark_task_terminal(run.task_id, 'canceled',
|
||||
'任务已取消' + (
|
||||
f"(已退回 {refunded} 次下载次数)" if refunded else ''))
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(run.task_id)
|
||||
if t is not None:
|
||||
@@ -369,29 +371,29 @@ def _finish_canceled(run: _ZipRun) -> None:
|
||||
f"{job.tag}已取消: {run.task_id}(成功{tally.ok} 退回{refunded}次)")
|
||||
|
||||
|
||||
def _finish_business_error(run: _ZipRun, exc: DownloadException) -> None:
|
||||
async def _finish_business_error(run: _ZipRun, exc: DownloadException) -> None:
|
||||
"""业务失败(清单阶段:无可下载条目 / 补扣下载次数失败 / 上游不可用)。
|
||||
|
||||
文案是我们自己拼的用户可读文本,保留原文(同播客单集下载)。
|
||||
"""
|
||||
job, tally = run.job, run.tally
|
||||
delivered = tally.ok if run.zip_valid else 0
|
||||
refunded = run.settle(run.task_id, delivered, 'error')
|
||||
_apply_error(run.task_id, str(exc), refunded)
|
||||
refunded = await run.settle(run.task_id, delivered, 'error')
|
||||
await _apply_error(run.task_id, str(exc), refunded)
|
||||
_discard(run.zip_tmp_path)
|
||||
api_service.logger.error(
|
||||
f"{job.tag}失败: {run.task_id} {exc}(成功{tally.ok} 退回{refunded}次)")
|
||||
|
||||
|
||||
def _finish_unexpected(run: _ZipRun, exc: Exception) -> None:
|
||||
async def _finish_unexpected(run: _ZipRun, exc: Exception) -> None:
|
||||
"""非预期异常:原文 logger 先行(结算本身可能再抛,先落下 traceback),
|
||||
用户可见文案泛化;带上退款结果再补一条,避免排障时只看到「异常」。"""
|
||||
job, tally = run.job, run.tally
|
||||
api_service.logger.error(f"{job.tag}异常: {run.task_id} {exc}\n{traceback.format_exc()}")
|
||||
delivered = tally.ok if run.zip_valid else 0
|
||||
refunded = run.settle(run.task_id, delivered, 'error')
|
||||
refunded = await run.settle(run.task_id, delivered, 'error')
|
||||
if delivered > 0 and run.zip_tmp_path:
|
||||
_apply_error(run.task_id, job.partial_msg(refunded), refunded)
|
||||
await _apply_error(run.task_id, job.partial_msg(refunded), refunded)
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(run.task_id)
|
||||
if t is not None:
|
||||
@@ -401,16 +403,16 @@ def _finish_unexpected(run: _ZipRun, exc: Exception) -> None:
|
||||
'audio_files': [],
|
||||
}
|
||||
else:
|
||||
_apply_error(run.task_id, '打包失败,请稍后重试' + (
|
||||
await _apply_error(run.task_id, '打包失败,请稍后重试' + (
|
||||
f"(已退回 {refunded} 次下载次数)" if refunded else ''), refunded)
|
||||
_discard(run.zip_tmp_path)
|
||||
api_service.logger.error(
|
||||
f"{job.tag}异常: {run.task_id}(成功{tally.ok} 退回{refunded}次)")
|
||||
|
||||
|
||||
def run_zip_job(job: ZipJob, task_id: str, *,
|
||||
settle: Callable[[str, int, str], int] = _settle_batch_billing) -> None:
|
||||
"""执行一次批量打包任务(在 worker 线程内调用,自身不向外抛异常)。
|
||||
async def run_zip_job(job: ZipJob, task_id: str, *,
|
||||
settle: Callable[[str, int, str], Awaitable[int]] = _settle_batch_billing) -> None:
|
||||
"""执行一次批量打包任务(在 worker 协程内调用,自身不向外抛异常)。
|
||||
|
||||
``settle`` 由调用方注入,默认走 :func:`services._taskcore._settle_batch_billing`。
|
||||
做成参数是为了让测试能在**模块级**替换结算函数(包装层在调用时读取模块全局,
|
||||
@@ -424,99 +426,91 @@ def run_zip_job(job: ZipJob, task_id: str, *,
|
||||
"""
|
||||
run = _ZipRun(job=job, task_id=task_id, settle=settle)
|
||||
try:
|
||||
_start_zip_run(run)
|
||||
_build_zip_archive(run)
|
||||
await _start_zip_run(run)
|
||||
await _build_zip_archive(run)
|
||||
|
||||
if run.tally.ok == 0:
|
||||
_finish_all_failed(run)
|
||||
await _finish_all_failed(run)
|
||||
return
|
||||
_publish_delivery(run)
|
||||
await _publish_delivery(run)
|
||||
except DownloadCanceled:
|
||||
_finish_canceled(run)
|
||||
await _finish_canceled(run)
|
||||
except DownloadException as e:
|
||||
_finish_business_error(run, e)
|
||||
await _finish_business_error(run, e)
|
||||
except Exception as e:
|
||||
_finish_unexpected(run, e)
|
||||
await _finish_unexpected(run, e)
|
||||
finally:
|
||||
# 回收信息预取线程池,避免线程泄漏(未启动的预取任务一并取消)
|
||||
job.cleanup()
|
||||
# 回收信息预取任务,避免任务泄漏(未启动的预取任务一并取消)
|
||||
await job.cleanup()
|
||||
|
||||
|
||||
def _apply_error(task_id: str, msg: str, refunded: int) -> None:
|
||||
async def _apply_error(task_id: str, msg: str, refunded: int) -> None:
|
||||
"""异常/业务失败的终态收敛:置 error(终态先到先得)、记账退款额。
|
||||
|
||||
走 :func:`_mark_task_terminal` 而非就地写任务字典——后者是播客侧的旧写法,
|
||||
除了重复一遍「已终态不覆盖」判断外,还漏掉了 worker 线程已死时按账本补结算
|
||||
的兜底(``/F-E``)。
|
||||
除了重复一遍「已终态不覆盖」判断外,还漏掉了 worker 已结束未结算时按账本
|
||||
补结算的兜底(``/F-E``)。
|
||||
"""
|
||||
_mark_task_terminal(task_id, 'error', msg)
|
||||
await _mark_task_terminal(task_id, 'error', msg)
|
||||
with DOWNLOAD_TASKS_LOCK:
|
||||
t = DOWNLOAD_TASKS.get(task_id)
|
||||
if t is not None:
|
||||
t['refunded'] = refunded
|
||||
|
||||
|
||||
def _fill_zip(job: ZipJob, items: list[Any], ctx: ZipContext, tally: _Tally,
|
||||
task: dict[str, Any], pause_ev: threading.Event) -> None:
|
||||
async def _fill_zip(job: ZipJob, items: list[Any], ctx: ZipContext, tally: _Tally,
|
||||
task: dict[str, Any], pause_ev) -> None:
|
||||
"""逐窗口下载并写入 ZIP(返回时中央目录尚未写出,由调用方的 with 退出时落盘)。
|
||||
|
||||
窗口 = ``job.concurrency`` 个条目:下载并行、落包串行。窗口大小取 1 时
|
||||
窗口 = ``job.concurrency`` 个条目:下载并发、落包串行。窗口大小取 1 时
|
||||
退化为顺序下载(播客整台即如此)。
|
||||
|
||||
取消语义与旧的线程池版本对齐:等待名额期间可被取消;窗口内某条抛
|
||||
DownloadCanceled 时整批中止(在途下载因每次分块都查取消位而很快退出)。
|
||||
"""
|
||||
concurrency = max(1, int(job.concurrency))
|
||||
pool: ThreadPoolExecutor | None = None
|
||||
try:
|
||||
# 不用 with 管理下载池——取消时 with 退出会 wait=True 等在途 future
|
||||
# (其内部阻塞在预取 HTTP 上最长 30s),改为不等待 + 取消排队任务
|
||||
pool = ThreadPoolExecutor(max_workers=concurrency)
|
||||
offset = 0
|
||||
while offset < len(items):
|
||||
if ctx.cancel_ev.is_set():
|
||||
raise DownloadCanceled("任务已取消")
|
||||
# 断线暂停:释放名额等待恢复/取消,恢复后重新进入排队
|
||||
_wait_if_paused(task, pause_ev, ctx.cancel_ev, tally.ok + len(tally.failed))
|
||||
# 每个窗口持有 BATCH_ZIP_SEM(同一时刻全局最多 N 个批量任务在下载)
|
||||
# 等待名额期间可被取消,不再无限阻塞线程与退款
|
||||
if not BATCH_ZIP_SEM.acquire_cancellable(ctx.cancel_ev):
|
||||
raise DownloadCanceled("任务已取消")
|
||||
try:
|
||||
# 暂停/取消落在「等待恢复返回」与「拿到名额」之间:立刻放名额回到
|
||||
# 循环顶部重新处理暂停(原播客侧缺这一步,会多下完这一集才停)
|
||||
if (ctx.cancel_ev.is_set() or pause_ev.is_set()
|
||||
or task['status'] == 'paused'):
|
||||
continue
|
||||
window = items[offset:offset + concurrency]
|
||||
start_idx = offset + 1 # 条目序号从 1 起(进度文案用)
|
||||
offset += len(window)
|
||||
job.prefetch(window, ctx) # 只预取本窗口
|
||||
futures = {
|
||||
pool.submit(job.download_one, item, start_idx + i, ctx): (item, start_idx + i)
|
||||
for i, item in enumerate(window)
|
||||
}
|
||||
for future in as_completed(futures):
|
||||
if ctx.cancel_ev.is_set():
|
||||
raise DownloadCanceled("任务已取消")
|
||||
item, idx = futures[future]
|
||||
try:
|
||||
payload = future.result()
|
||||
# 落包在主线程:ZipFile 非线程安全 + 包内名去重要串行
|
||||
job.write_entry(item, idx, payload, ctx)
|
||||
except DownloadCanceled:
|
||||
raise
|
||||
except ItemFailed as f:
|
||||
tally.failed.append(f.label)
|
||||
except Exception as e:
|
||||
tally.failed.append(f"{job.fail_label(item)}({e})")
|
||||
else:
|
||||
tally.ok += 1
|
||||
ctx.progress(job.done_msg(item, idx, ctx))
|
||||
finally:
|
||||
BATCH_ZIP_SEM.release()
|
||||
finally:
|
||||
if pool is not None:
|
||||
try:
|
||||
# 取消/异常时不等待在途下载线程(其可能阻塞在预取 HTTP 上),
|
||||
# 排队任务一并取消;在途线程自行收尾(.part 残片由续传/清扫兜底)
|
||||
pool.shutdown(wait=False, cancel_futures=True)
|
||||
except TypeError:
|
||||
pool.shutdown(wait=False)
|
||||
offset = 0
|
||||
while offset < len(items):
|
||||
if ctx.cancel_ev.is_set():
|
||||
raise DownloadCanceled("任务已取消")
|
||||
# 断线暂停:释放名额等待恢复/取消,恢复后重新进入排队
|
||||
await _wait_if_paused(task, pause_ev, ctx.cancel_ev, tally.ok + len(tally.failed))
|
||||
# 每个窗口持有 BATCH_ZIP_SEM(同一时刻全局最多 N 个批量任务在下载)
|
||||
# 等待名额期间可被取消,不再无限等待与延迟退款
|
||||
if not await BATCH_ZIP_SEM.acquire_cancellable(ctx.cancel_ev):
|
||||
raise DownloadCanceled("任务已取消")
|
||||
try:
|
||||
# 暂停/取消落在「等待恢复返回」与「拿到名额」之间:立刻放名额回到
|
||||
# 循环顶部重新处理暂停(原播客侧缺这一步,会多下完这一集才停)
|
||||
if (ctx.cancel_ev.is_set() or pause_ev.is_set()
|
||||
or task['status'] == 'paused'):
|
||||
continue
|
||||
window = items[offset:offset + concurrency]
|
||||
start_idx = offset + 1 # 条目序号从 1 起(进度文案用)
|
||||
offset += len(window)
|
||||
await job.prefetch(window, ctx) # 只预取本窗口
|
||||
results = await asyncio.gather(
|
||||
*(job.download_one(item, start_idx + i, ctx)
|
||||
for i, item in enumerate(window)),
|
||||
return_exceptions=True,
|
||||
)
|
||||
for i, result in enumerate(results):
|
||||
if ctx.cancel_ev.is_set():
|
||||
raise DownloadCanceled("任务已取消")
|
||||
item, idx = window[i], start_idx + i
|
||||
try:
|
||||
if isinstance(result, BaseException):
|
||||
raise result
|
||||
# 落包串行:ZipFile 非并发安全 + 包内名去重要按序
|
||||
await job.write_entry(item, idx, result, ctx)
|
||||
except DownloadCanceled:
|
||||
raise
|
||||
except ItemFailed as f:
|
||||
tally.failed.append(f.label)
|
||||
except Exception as e:
|
||||
tally.failed.append(f"{job.fail_label(item)}({e})")
|
||||
else:
|
||||
tally.ok += 1
|
||||
ctx.progress(job.done_msg(item, idx, ctx))
|
||||
finally:
|
||||
BATCH_ZIP_SEM.release()
|
||||
+40
-32
@@ -5,11 +5,8 @@
|
||||
本模块只保留「音乐歌单」这一侧的策略:窗口化预取与并行下载、每首三条目
|
||||
(音频 + 歌词 + 封面)入包、同名去重、包名与文案。
|
||||
"""
|
||||
import asyncio
|
||||
import zipfile
|
||||
from concurrent.futures import (
|
||||
Future,
|
||||
ThreadPoolExecutor,
|
||||
)
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -38,7 +35,7 @@ from .api_service import (
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _SongPayload:
|
||||
"""一首歌下载完成后的入包素材(下载线程产出,落包线程消费)。"""
|
||||
"""一首歌下载完成后的入包素材(下载协程产出,落包协程消费)。"""
|
||||
|
||||
path: str
|
||||
name: str
|
||||
@@ -59,36 +56,41 @@ class _SonglistZipJob(ZipJob):
|
||||
record_duration = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._info_pool: ThreadPoolExecutor | None = None
|
||||
self._info_futures: dict[Any, Future[Any]] = {}
|
||||
self._info_sem: asyncio.Semaphore | None = None
|
||||
self._info_tasks: dict[Any, asyncio.Task[Any]] = {}
|
||||
|
||||
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]:
|
||||
self.concurrency = int(params['concurrency'])
|
||||
return list(params['ids'])
|
||||
|
||||
def prefetch(self, window: list[Any], ctx: ZipContext) -> None:
|
||||
async def prefetch(self, window: list[Any], ctx: ZipContext) -> None:
|
||||
"""按窗口预取歌曲信息。
|
||||
|
||||
原实现一次性提交全部(最多 500 首 ×3 接口)预取任务,大歌单瞬间以 10 并发
|
||||
连发上游约 1500 次请求打风控;改为每个下载窗口只预取本窗口的歌(与下载节奏
|
||||
对齐),``download_one`` 语义不变(等预取结果再下载)。
|
||||
对齐),并发另用信号量钳在 4,``download_one`` 语义不变(等预取结果再下载)。
|
||||
"""
|
||||
if self._info_pool is None:
|
||||
self._info_pool = ThreadPoolExecutor(max_workers=min(4, max(1, self.concurrency)))
|
||||
if self._info_sem is None:
|
||||
self._info_sem = asyncio.Semaphore(min(4, max(1, self.concurrency)))
|
||||
quality = ctx.params['quality']
|
||||
cookies = ctx.params['cookies']
|
||||
for mid in window:
|
||||
if mid not in self._info_futures:
|
||||
self._info_futures[mid] = self._info_pool.submit(
|
||||
api_service.downloader.get_music_info, mid, quality, cookies
|
||||
)
|
||||
if mid not in self._info_tasks:
|
||||
self._info_tasks[mid] = asyncio.create_task(
|
||||
self._load_info(mid, quality, cookies))
|
||||
|
||||
def download_one(self, item: Any, idx: int, ctx: ZipContext) -> _SongPayload:
|
||||
async def _load_info(self, mid: Any, quality: str, cookies: dict[str, str]) -> Any:
|
||||
"""取单曲信息;并发由 _info_sem 钳制(避免预取风暴打风控)。"""
|
||||
assert self._info_sem is not None
|
||||
async with self._info_sem:
|
||||
return await api_service.downloader.get_music_info(mid, quality, cookies)
|
||||
|
||||
async def download_one(self, item: Any, idx: int, ctx: ZipContext) -> _SongPayload:
|
||||
"""并行下载单元:等待预取信息 → 下载 → 复用预取歌词与缓存封面(零重复请求)。"""
|
||||
mid = item
|
||||
info = self._info_futures[mid].result()
|
||||
info = await self._info_tasks[mid]
|
||||
params = ctx.params
|
||||
result = api_service.downloader.download_music_file(
|
||||
result = await api_service.downloader.download_music_file(
|
||||
mid, params['quality'],
|
||||
write_meta=params['write_meta'],
|
||||
meta_fields=params['meta_fields'],
|
||||
@@ -103,7 +105,7 @@ class _SonglistZipJob(ZipJob):
|
||||
lyric = getattr(info, 'lyric', '') or ''
|
||||
# 封面走共享缓存(同一专辑只拉一次网络);取消后不再发起新请求
|
||||
if not ctx.cancel_ev.is_set() and info.pic_url:
|
||||
cover = fetch_cover_bytes(info.pic_url) or b''
|
||||
cover = await fetch_cover_bytes(info.pic_url) or b''
|
||||
if not result.success:
|
||||
raise ItemFailed(str(mid))
|
||||
assert result.file_path is not None
|
||||
@@ -118,7 +120,7 @@ class _SonglistZipJob(ZipJob):
|
||||
return _SongPayload(path=result.file_path, name=mi.name, artists=mi.artists,
|
||||
file_type=mi.file_type, lyric=lyric, cover=cover)
|
||||
|
||||
def write_entry(self, item: Any, idx: int, payload: _SongPayload, ctx: ZipContext) -> None:
|
||||
async def write_entry(self, item: Any, idx: int, payload: _SongPayload, ctx: ZipContext) -> None:
|
||||
mid = item
|
||||
base = _build_download_base(ctx.params['filename_format'],
|
||||
{'name': payload.name, 'artist_string': payload.artists})
|
||||
@@ -139,13 +141,15 @@ class _SonglistZipJob(ZipJob):
|
||||
k += 1
|
||||
ctx.used_arcnames.update((final_name, lrc_name, jpg_name))
|
||||
# F-D:exists 与 zf.write 之间的缓存竞态(另一任务缓存 miss 删文件)
|
||||
# 按单曲失败计,不再让整批转 error
|
||||
# 按单曲失败计,不再让整批转 error。音频条目可达上百 MB,落盘经 to_thread
|
||||
# 卸载,避免在事件循环里做整段文件拷贝
|
||||
try:
|
||||
ctx.zf.write(payload.path, arcname=final_name, compress_type=zipfile.ZIP_STORED)
|
||||
await asyncio.to_thread(ctx.zf.write, payload.path, arcname=final_name,
|
||||
compress_type=zipfile.ZIP_STORED)
|
||||
except OSError as e:
|
||||
raise ItemFailed(f"{mid}(缓存文件读取失败: {e})") from e
|
||||
# 缓存文件是跨任务共享资源,任务不得删除;磁盘回收交给监控线程的下载缓存
|
||||
# 清扫(按文件年龄)。歌词与封面已在并行下载线程中拉取,这里直接写包(无网络等待)
|
||||
# 清扫(按文件年龄)。歌词与封面已在并行下载协程中拉取,这里直接写包(无网络等待)
|
||||
if payload.lyric:
|
||||
try:
|
||||
ctx.zf.writestr(lrc_name, _format_lyric(payload.lyric, lyric_format),
|
||||
@@ -161,19 +165,23 @@ class _SonglistZipJob(ZipJob):
|
||||
def zip_filename(self, ok_count: int) -> str:
|
||||
return f"批量下载_{ok_count}首.zip"
|
||||
|
||||
def cleanup(self) -> None:
|
||||
if self._info_pool is not None:
|
||||
try:
|
||||
self._info_pool.shutdown(wait=False, cancel_futures=True)
|
||||
except TypeError:
|
||||
self._info_pool.shutdown(wait=False)
|
||||
async def cleanup(self) -> None:
|
||||
"""取消在途预取任务(窗口因暂停/取消被跳过时它们没人 await)。
|
||||
|
||||
取消后不再 await:asyncio 任务被 cancel 不会产生"异常未被取用"告警,
|
||||
而 await 会在此处引入最长一次上游请求的等待。
|
||||
"""
|
||||
for task in self._info_tasks.values():
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
self._info_tasks.clear()
|
||||
|
||||
|
||||
def _batch_zip_worker(task_id: str) -> None:
|
||||
async def _batch_zip_worker(task_id: str) -> None:
|
||||
"""后台批量打包:窗口化下载 → 写 ZIP(音频免压缩),支持取消与断线暂停
|
||||
|
||||
- 断线暂停:设备心跳超时后,当前窗口下载完即释放 BATCH_ZIP_SEM 名额给下一位,
|
||||
保存进度进入暂停等待;重新打开网站(心跳恢复)后自动回到队列继续下载
|
||||
- 音频入包即删,缓解磁盘占用
|
||||
"""
|
||||
run_zip_job(_SonglistZipJob(), task_id, settle=_settle_batch_billing)
|
||||
await run_zip_job(_SonglistZipJob(), task_id, settle=_settle_batch_billing)
|
||||
+57
-41
@@ -7,8 +7,13 @@
|
||||
``_single_download_worker`` 原是 177 行 / 圈复杂度 30 的单函数,三个 except 分支
|
||||
各写一遍「结算 + 删任务目录」,正文里又散着四处取消检查。此处按「一步一个具名
|
||||
函数」拆开:主函数只留线性流程,失败收尾收敛到 ``_fail_single_task`` 一处。
|
||||
|
||||
worker 自本轮起是协程:下载链路本身已异步,落库/删目录等阻塞调用经
|
||||
``asyncio.to_thread`` 卸载(auth_system 仍是同步 SQLite,DB 线异步化后即可
|
||||
直接 await)。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
@@ -114,13 +119,13 @@ def _begin_single_task(task_id: str) -> SingleTaskParams:
|
||||
)
|
||||
|
||||
|
||||
def _fetch_single_metadata(p: SingleTaskParams) -> tuple[MusicInfo, dict[str, Any], str, str]:
|
||||
"""一次预取歌曲完整信息(URL/详情/歌词三接口并行),并算出交付基础名。
|
||||
async def _fetch_single_metadata(p: SingleTaskParams) -> tuple[MusicInfo, dict[str, Any], str, str]:
|
||||
"""一次预取歌曲完整信息(URL/详情/歌词三接口并发),并算出交付基础名。
|
||||
|
||||
替代原先 name_v1 + url_v1 + 下载器内部 get_music_info 的重复串行调用。
|
||||
返回 ``(MusicInfo, 下载器口径的 music_info, base, filename)``。
|
||||
"""
|
||||
mi = api_service.downloader.get_music_info(p.music_id, p.quality, p.cookies)
|
||||
mi = await api_service.downloader.get_music_info(p.music_id, p.quality, p.cookies)
|
||||
music_info = {
|
||||
'id': p.music_id,
|
||||
'name': mi.name,
|
||||
@@ -188,37 +193,47 @@ def _single_file_result(file_path_str: str, filename: str,
|
||||
}
|
||||
|
||||
|
||||
def _pack_single_zip(file_path_str: str, base: str, filename: str, mi: MusicInfo,
|
||||
music_info: dict[str, Any], p: SingleTaskParams) -> dict[str, Any]:
|
||||
async def _pack_single_zip(file_path_str: str, base: str, filename: str, mi: MusicInfo,
|
||||
music_info: dict[str, Any], p: SingleTaskParams) -> dict[str, Any]:
|
||||
"""把音频 + 歌词 + 封面 + info.txt 打成单曲 ZIP 交付包。
|
||||
|
||||
歌词与封面都是**尽力而为**:歌词在预取时已一并拿到(无需再请求一次),
|
||||
封面走共享缓存;两者拿不到就不写对应条目,不影响音频交付。
|
||||
ZIP 组装是整段文件拷贝的阻塞 IO,经 to_thread 卸载。
|
||||
"""
|
||||
import tempfile as _tempfile
|
||||
|
||||
# 封面走共享缓存(与元数据写入共用同一次网络请求)——先取好再落包,
|
||||
# 网络等待留在事件循环里(协程),文件写入整段交给线程
|
||||
cover: bytes = b''
|
||||
if mi.pic_url:
|
||||
cover = await fetch_cover_bytes(mi.pic_url) or b''
|
||||
|
||||
fd, zip_tmp_path = _tempfile.mkstemp(prefix='single_zip_', suffix='.zip',
|
||||
dir=str(Path(file_path_str).parent))
|
||||
os.close(fd)
|
||||
with zipfile.ZipFile(zip_tmp_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.write(file_path_str, arcname=filename)
|
||||
# 歌词已在预取时一并拿到,无需再请求一次
|
||||
if mi.lyric:
|
||||
try:
|
||||
zf.writestr(f"{base}.{p.lyric_format}", _format_lyric(mi.lyric, p.lyric_format))
|
||||
except Exception:
|
||||
pass
|
||||
# 封面走共享缓存(与元数据写入共用同一次网络请求)
|
||||
cover = fetch_cover_bytes(mi.pic_url)
|
||||
if cover:
|
||||
zf.writestr(f"{base}.jpg", cover)
|
||||
info_txt = (
|
||||
f"歌曲: {music_info['name']}\n"
|
||||
f"歌手: {music_info['artist_string']}\n"
|
||||
f"专辑: {music_info['album']}\n"
|
||||
f"音质: {api_service._get_quality_display_name(p.quality)}\n"
|
||||
)
|
||||
zf.writestr("info.txt", info_txt)
|
||||
|
||||
def _write_zip() -> None:
|
||||
with zipfile.ZipFile(zip_tmp_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.write(file_path_str, arcname=filename)
|
||||
# 歌词已在预取时一并拿到,无需再请求一次
|
||||
if mi.lyric:
|
||||
try:
|
||||
zf.writestr(f"{base}.{p.lyric_format}",
|
||||
_format_lyric(mi.lyric, p.lyric_format))
|
||||
except Exception:
|
||||
pass
|
||||
if cover:
|
||||
zf.writestr(f"{base}.jpg", cover)
|
||||
info_txt = (
|
||||
f"歌曲: {music_info['name']}\n"
|
||||
f"歌手: {music_info['artist_string']}\n"
|
||||
f"专辑: {music_info['album']}\n"
|
||||
f"音质: {api_service._get_quality_display_name(p.quality)}\n"
|
||||
)
|
||||
zf.writestr("info.txt", info_txt)
|
||||
|
||||
await asyncio.to_thread(_write_zip)
|
||||
return {
|
||||
'file_path': file_path_str,
|
||||
'zip_path': zip_tmp_path,
|
||||
@@ -228,8 +243,8 @@ def _pack_single_zip(file_path_str: str, base: str, filename: str, mi: MusicInfo
|
||||
}
|
||||
|
||||
|
||||
def _publish_single_task(task_id: str, result: dict[str, Any], remote_ip: str,
|
||||
name: str, filename: str) -> None:
|
||||
async def _publish_single_task(task_id: str, result: dict[str, Any], remote_ip: str,
|
||||
name: str, filename: str) -> None:
|
||||
"""最终发布:置 done(已终态不覆盖)→ 结算 → 记操作日志。
|
||||
|
||||
交付已落定;结算失败**不再**把任务改标 error——钱由重启对账兜底,
|
||||
@@ -246,7 +261,7 @@ def _publish_single_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:
|
||||
@@ -256,30 +271,30 @@ def _publish_single_task(task_id: str, result: dict[str, Any], remote_ip: str,
|
||||
api_service.logger.info(f"单曲下载完成: {filename} ({task_id})")
|
||||
|
||||
|
||||
def _fail_single_task(task_id: str, status: str, msg: str, ledger_status: str,
|
||||
task_dir_path: str | None) -> None:
|
||||
async def _fail_single_task(task_id: str, status: str, msg: str, ledger_status: str,
|
||||
task_dir_path: str | None) -> None:
|
||||
"""失败/取消的统一收尾:置终态 → 退款 → 清掉任务目录。
|
||||
|
||||
这三个 except 分支原先各写一遍(共 9 行 × 3 处);收敛后新增一种失败
|
||||
只需要挑一个 ``ledger_status``,不会再漏掉清理或退款。
|
||||
"""
|
||||
_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_path:
|
||||
shutil.rmtree(task_dir_path, ignore_errors=True)
|
||||
await asyncio.to_thread(shutil.rmtree, task_dir_path, ignore_errors=True)
|
||||
|
||||
|
||||
def _single_download_worker(task_id: str) -> None:
|
||||
async def _single_download_worker(task_id: str) -> None:
|
||||
"""后台单曲下载:下载音频(可选 ZIP 打包),支持取消;完成后由 /download/result 交付,35 分钟保留期清理"""
|
||||
task_dir_path: str | None = None
|
||||
try:
|
||||
p = _begin_single_task(task_id)
|
||||
mi, music_info, base, filename = _fetch_single_metadata(p)
|
||||
mi, music_info, base, filename = await _fetch_single_metadata(p)
|
||||
|
||||
download_result = api_service.downloader.download_music_file(
|
||||
download_result = await api_service.downloader.download_music_file(
|
||||
p.music_id, p.quality,
|
||||
write_meta=p.write_meta,
|
||||
meta_fields=p.meta_fields,
|
||||
@@ -293,25 +308,26 @@ def _single_download_worker(task_id: str) -> None:
|
||||
_abort_if_canceled(p.cancel_ev)
|
||||
assert download_result.file_path is not None
|
||||
# 交付文件用任务专属副本,共享缓存不进清理清单
|
||||
file_path_str = _task_delivery_copy(task_id, Path(download_result.file_path), filename)
|
||||
file_path_str = await asyncio.to_thread(
|
||||
_task_delivery_copy, task_id, Path(download_result.file_path), filename)
|
||||
task_dir_path = str(Path(file_path_str).parent)
|
||||
|
||||
if p.need_zip:
|
||||
result = _pack_single_zip(file_path_str, base, filename, mi, music_info, p)
|
||||
result = await _pack_single_zip(file_path_str, base, filename, mi, music_info, p)
|
||||
else:
|
||||
result = _single_file_result(file_path_str, filename, music_info)
|
||||
# 打包阶段同样以取消检查收口
|
||||
_abort_if_canceled(p.cancel_ev)
|
||||
|
||||
_publish_single_task(task_id, result, p.remote_ip, music_info['name'], filename)
|
||||
await _publish_single_task(task_id, result, p.remote_ip, music_info['name'], filename)
|
||||
except DownloadCanceled:
|
||||
api_service.logger.info(f"单曲下载已取消: {task_id}")
|
||||
_fail_single_task(task_id, 'canceled', '任务已取消', 'canceled', task_dir_path)
|
||||
await _fail_single_task(task_id, 'canceled', '任务已取消', 'canceled', task_dir_path)
|
||||
except DownloadException as e:
|
||||
api_service.logger.error(f"单曲下载失败: {task_id} {e}")
|
||||
_fail_single_task(task_id, 'error', str(e), 'error', task_dir_path)
|
||||
await _fail_single_task(task_id, 'error', str(e), 'error', task_dir_path)
|
||||
except Exception as e:
|
||||
# 非预期异常的 repr 可能含上游主机/连接细节——用户可见文案
|
||||
# 泛化为固定文案,原文 logger 先行留档(教训:先记录再泛化)
|
||||
api_service.logger.error(f"单曲下载异常: {task_id} {e}\n{traceback.format_exc()}")
|
||||
_fail_single_task(task_id, 'error', '下载失败,请稍后重试', 'error', task_dir_path)
|
||||
await _fail_single_task(task_id, 'error', '下载失败,请稍后重试', 'error', task_dir_path)
|
||||
+89
-71
@@ -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)
|
||||
@@ -1,61 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""同步流式响应垫片(音频分段透传)。
|
||||
"""
|
||||
|
||||
|
||||
|
||||
class _SyncStreamResponse:
|
||||
"""同步流式响应包装(把 aiohttp 的异步流按需拉成同步迭代)。
|
||||
|
||||
供流式下载使用:worker 是同步线程,这里经 core.async_bridge 在后台事件循环
|
||||
逐块取数据,避免引入 requests 依赖(Flask 已删除、requests 已移出依赖)。
|
||||
"""
|
||||
|
||||
def __init__(self, url: str, timeout: float):
|
||||
from core import async_bridge
|
||||
self._bridge = async_bridge
|
||||
self._url = url
|
||||
self._timeout = timeout
|
||||
self._agent = None
|
||||
self.status = 0
|
||||
self.headers: dict[str, str] = {}
|
||||
self._resp = None
|
||||
|
||||
def __enter__(self):
|
||||
self._agent = self._bridge.run_sync(self._open())
|
||||
self.status = self._agent[0]
|
||||
self.headers = self._agent[1]
|
||||
return self
|
||||
|
||||
async def _open(self):
|
||||
from core.http_client import client
|
||||
resp = await client.open('GET', self._url, 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/',
|
||||
}, timeout=self._timeout)
|
||||
return resp.status, dict(resp.headers), resp
|
||||
|
||||
def iter_content(self, chunk_size: int = 256 * 1024):
|
||||
assert self._agent is not None
|
||||
resp = self._agent[2]
|
||||
it = resp.content.iter_chunked(chunk_size)
|
||||
while True:
|
||||
try:
|
||||
chunk = self._bridge.run_sync(it.__anext__())
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
yield chunk
|
||||
|
||||
def __exit__(self, *exc):
|
||||
if self._agent is not None and self._agent[2] is not None:
|
||||
try:
|
||||
self._agent[2].close()
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _stream_open(url: str, timeout: float = 60) -> _SyncStreamResponse:
|
||||
"""打开同步可迭代的流式响应(见 _SyncStreamResponse)。"""
|
||||
return _SyncStreamResponse(url, timeout)
|
||||
+4
-4
@@ -172,7 +172,7 @@ def _reap_finished_tasks(now: float) -> None:
|
||||
def _cancel_overtime_tasks(now: float) -> None:
|
||||
"""运行/排队/暂停超过硬上限仍未结束的任务 → 置取消并唤醒 cancel Event。
|
||||
|
||||
worker 线程已死则无人再走终态结算,监控代为按账本退款——ledger_settle 幂等,
|
||||
worker 已结束则无人再走终态结算,监控代为按账本退款——ledger_settle 幂等,
|
||||
worker 若已结算过此处返回 0,无双退。结算移到任务锁外(同 _mark_task_terminal
|
||||
口径):库忙 15s 不再随任务锁波及全站任务端点。
|
||||
"""
|
||||
@@ -188,9 +188,9 @@ def _cancel_overtime_tasks(now: float) -> None:
|
||||
task['cancel'].set()
|
||||
except Exception:
|
||||
pass
|
||||
# worker 线程已死则无人再走终态结算——监控代为按账本结算退款
|
||||
th = task.get('worker_thread')
|
||||
if th is not None and not th.is_alive():
|
||||
# worker 已结束则无人再走终态结算——监控代为按账本结算退款
|
||||
wt = task.get('worker_task')
|
||||
if wt is not None and wt.done():
|
||||
timeout_settle.append(tid)
|
||||
api_service.logger.warning(f"任务超时自动取消: {tid}")
|
||||
for tid in timeout_settle:
|
||||
|
||||
Reference in new issue
Block a user