diff --git a/app/application/torrent/download.py b/app/application/torrent/download.py index 28bd72cce..fc6b451ec 100644 --- a/app/application/torrent/download.py +++ b/app/application/torrent/download.py @@ -1,4 +1,5 @@ import datetime +import json import re import time from functools import lru_cache @@ -40,6 +41,24 @@ class TorrentResponsePort(Protocol): reason: str +def _torrent_rate_limit_error(response: Optional[TorrentResponsePort]) -> Optional[str]: + """在种子解析前提取明确的 JSON 限流提示;HTTP 429 保留既有流控错误。""" + if response is None: + return None + content = response.content + if content.lstrip().startswith(b"{"): + try: + payload = json.loads(content) + except (ValueError, UnicodeError): + payload = {} + message = payload.get("message") or payload.get("msg") + if isinstance(message, str) and torrent_rules.rate_limit_cooldown(message) is not None: + return f"站点限流:{message}" + if response.status_code == 429: + return "触发站点流控,请稍后重试" + return None + + class TorrentHttpPort(Protocol): """声明种子下载所需的同步 GET/POST 能力。""" @@ -159,9 +178,11 @@ class TorrentHelper: return None def _should_retry_torrent_response(self, response: Optional[TorrentResponsePort]) -> bool: - """保留重定向、磁力和首次下载确认页,仅重试网络失败及无效的种子响应。""" + """保留重定向、磁力和首次确认页,明确限流不得消耗瞬时重试预算。""" if response is None: return True + if _torrent_rate_limit_error(response): + return False if response.status_code != 200: return _is_transient_torrent_status(response.status_code) content = response.content @@ -225,6 +246,8 @@ class TorrentHelper: url=url, cookie=cookie, ua=ua, referer=referer, proxies=config.proxy if proxy else None, allow_redirects=False, ) + if rate_limit_error := _torrent_rate_limit_error(req): + return cache_path, None, "", [], rate_limit_error if req is not None and req.status_code == 200: if not req.content: return cache_path, None, "", [], "未下载到种子数据" @@ -289,8 +312,6 @@ class TorrentHelper: return cache_path, None, "", [], "种子数据有误,请确认链接是否正确" elif req is None: return cache_path, None, "", [], "无法打开链接" - elif req.status_code == 429: - return cache_path, None, "", [], "触发站点流控,请稍后重试" else: # 把错误的种子记下来,避免重复使用 if cache_invalid and not _is_transient_torrent_status(req.status_code): diff --git a/app/chain/download/failure.py b/app/chain/download/failure.py index 31726ea05..d75910a54 100644 --- a/app/chain/download/failure.py +++ b/app/chain/download/failure.py @@ -14,6 +14,7 @@ from app.application.download.failures import ( ) from app.chain.download.contract import _DownloadOwnerBase from app.domain import episode as episode_rules +from app.domain import torrent as torrent_rules from app.domain.context import ( Context, TorrentInfo, @@ -129,8 +130,11 @@ class DownloadFailureOwner(_DownloadOwnerBase): @staticmethod def _download_failure_ttl(error_msg: Optional[str]) -> int: """ - 按失败原因确定资源冷却时间;泛化的空内容不能证明资源失效,使用瞬时冷却。 + 限流按站点窗口冷却;泛化的空内容不能证明资源失效,使用瞬时冷却。 """ + rate_limit_ttl = torrent_rules.rate_limit_cooldown(error_msg) + if rate_limit_ttl is not None: + return rate_limit_ttl error_text = str(error_msg or "").lower() if any(keyword in error_text for keyword in DOWNLOAD_FAILURE_RESOURCE_ERROR_KEYWORDS): return DOWNLOAD_FAILURE_RESOURCE_TTL_SECONDS diff --git a/app/chain/download/submission.py b/app/chain/download/submission.py index 383bdef02..3fd51a6c3 100644 --- a/app/chain/download/submission.py +++ b/app/chain/download/submission.py @@ -5,7 +5,7 @@ import json import re from dataclasses import dataclass from pathlib import Path -from typing import Any, Dict, Optional, Set, Tuple, Union, cast +from typing import Any, Callable, Dict, Optional, Set, Tuple, Union, cast from urllib.parse import urlencode, urljoin, urlparse from app.application.configuration import get_chain_runtime_config_snapshot @@ -175,10 +175,12 @@ class _DownloadResourceOwner(_DownloadOwnerBase): def download_torrent(self, torrent: TorrentInfo, channel: Optional[NotificationChannel] = None, source: Optional[str] = None, - userid: Union[str, int, None] = None + userid: Union[str, int, None] = None, + on_failure: Optional[Callable[[str], None]] = None, ) -> Tuple[Optional[Union[str, bytes]], str, list[str]]: """ 下载种子文件,如果是磁力链,会返回磁力链接本身 + :param on_failure: 将本次具体失败原因交还准备流程,保持返回元组与并发调用隔离 :return: 种子内容,种子目录名,种子文件清单 """ # 获取下载链接 @@ -213,6 +215,8 @@ class _DownloadResourceOwner(_DownloadOwnerBase): return content, "", [] if not content: + if on_failure: + on_failure(error_msg or "下载种子内容为空") logger.error(f"下载种子文件失败:{torrent.title}") self.post_message(Message( channel=channel, @@ -455,9 +459,18 @@ class DownloadSubmissionOwner(_DownloadResourceOwner): context.selected_episodes = sorted(set(meta.episode_list)) else: context.selected_episodes = [] + download_error = "下载种子内容为空" + + def remember_rate_limit(error_msg: str) -> None: + """仅保留本次限流原因,避免准备流程用空内容覆盖站点冷却窗口。""" + nonlocal download_error + if torrent_rules.rate_limit_cooldown(error_msg) is not None: + download_error = error_msg + if not torrent_file and not torrent_content: torrent_content, _, _ = self.download_torrent( - torrent, channel=channel, source=source, userid=userid + torrent, channel=channel, source=source, userid=userid, + on_failure=remember_rate_limit, ) elif torrent_file: torrent_content = ( @@ -471,12 +484,12 @@ class DownloadSubmissionOwner(_DownloadResourceOwner): if not torrent_content: self._record_download_failure( context=context, - error_msg="下载种子内容为空", + error_msg=download_error, downloader=downloader or site_downloader, source=source, episodes=episodes, ) - return None, "下载种子内容为空" + return None, download_error folder_name, file_list = cast(Any, TorrentHelper)().get_fileinfo_from_torrent_content( torrent_content ) diff --git a/app/domain/torrent.py b/app/domain/torrent.py index 0c9710c79..3cadde3f2 100644 --- a/app/domain/torrent.py +++ b/app/domain/torrent.py @@ -56,3 +56,31 @@ def is_expiring_download_url(url: Optional[str]) -> bool: except ValueError: return False return bool(params.get("t") and params.get("sign")) + + +def rate_limit_cooldown(message: Optional[str]) -> Optional[int]: + """识别种子下载限流语义并返回冷却秒数;未知错误返回空。 + + 每日下载配额采用完整 24 小时以覆盖站点时区;短期限流沿用至少一小时的 + 订阅冷却,提示更长等待时按提示延长,不在下载调用内立即重试。 + """ + text = str(message or "").lower() + daily_quota = ( + re.search(r"[当當]天|每天|每日|今日|daily", text) + and re.search(r"下载|下載|download", text) + and re.search(r"最多|上限|限[额額]|次[数數]|limit|quota", text) + ) + if daily_quota: + return 86400 + keywords = ("限流", "流控", "请求太多", "请求过多", "请求频繁", "请求过于频繁", + "請求太多", "請求過多", "請求頻繁", "請求過於頻繁", "too many requests", "rate limit") + if not any(keyword in text for keyword in keywords): + return None + wait = re.search(r"(\d+)\s*(秒|分[钟鐘]?|小[时時]|seconds?|minutes?|hours?)", text) + if not wait: + return 3600 + unit = wait.group(2) + multiplier = 3600 if unit.startswith(("小", "hour")) else ( + 60 if unit.startswith(("分", "minute")) else 1 + ) + return max(3600, int(wait.group(1)) * multiplier) diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index 6521ec1ce..083e77091 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -763,7 +763,7 @@ flowchart LR | 指标 | 当前值 | |---|---:| | Python 模块 | 1114 | -| 内部导入边 | 9,429 | +| 内部导入边 | 9,430 | | 非平凡 SCC | 1(精确 containment 的 TMDB 移植包环) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 49(债务已清零,49 条精确 containment) | @@ -773,7 +773,7 @@ flowchart LR | Model/Oper 自动事务与自建 Session | 0 | | 组合根外 `SystemConfigOper()` | 0 | -整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;音乐标签准入与批次共识由 `app.chain.transfer.music` 负责,预览证据由 `app.application.transfer.projection` 只读投影;宿主依赖边现为 9,429;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条模块导入边;资源过滤动作 `app.workflow.actions.filter_torrents` 与动作包共用的领域还原函数同样把 Schema 资源还原为领域对象后再交给过滤链,新增 6 条模块导入边。音乐来源链与识别缓存复用领域身份核验,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。缓存组合根只在启动时选用 Redis 缓存才导入 Redis 适配器,依赖 langchain_core 的对话记忆模型归属 `app.agent.memory`,文件缓存且未启用智能体的实例不再加载 redis 与 langchain_core。Telegram 渠道改用模块内 `app.modules.telegram.botapi` 精简 Bot API 客户端,经 `RequestUtils` 出站,宿主不再导入 pyTelegramBotAPI,启用 Telegram 的实例也不会因该 SDK 加载 redis;该依赖暂时保留给插件使用。Web Push 协议(aes128gcm 加密、VAPID 签名与经 `RequestUtils` 投递)由网络适配器 `app.adapters.network.webpush` 直接基于 http-ece 与 py-vapid 实现,消息端点与 `WebPushModule` 共用,宿主不再导入 pywebpush 及其连带的 aiohttp;该依赖同样暂时保留给插件使用。飞书渠道改用模块内 `app.modules.feishu.openapi` OpenAPI 客户端(经 `RequestUtils` 出站)与网络适配器 `app.adapters.network.feishu` 事件长连接(websocket-client 同步收发 pbbp2 帧),宿主不再导入 lark-oapi 及其上万个生成模块,长连接也不再依赖 SDK 的模块级事件循环;插件经 `app.sdk.feishu` 复用同一长连接,lark-oapi 暂时保留给尚未迁移的插件使用。API 文档路由由 `app.adapters.web.docs` 按 `API_DOCS_ENABLE` 逐请求开放,默认关闭,未开放时不生成文档。当前 `app.startup.lifecycle` 为 582、`app.factory` 为 595、`app.main` 为 597。音乐调用观察 `app.application.music.observation` 新增一个轻量模块,记录来源结果及请求预算;AcoustID及路径识别复用此上下文传递有界指纹候选,保留旧单ID模块合同。站点图片域名快照新增 `app.application.security.image`,各启动入口增加一个模块;性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。 +整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;音乐标签准入与批次共识由 `app.chain.transfer.music` 负责,预览证据由 `app.application.transfer.projection` 只读投影;宿主依赖边现为 9,430;种子下载限流窗口由 `app.domain.torrent` 定义,失败冷却 owner 复用同一语义,新增 1 条合法 Chain 到 Domain 的导入边;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条模块导入边;资源过滤动作 `app.workflow.actions.filter_torrents` 与动作包共用的领域还原函数同样把 Schema 资源还原为领域对象后再交给过滤链,新增 6 条模块导入边。音乐来源链与识别缓存复用领域身份核验,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。缓存组合根只在启动时选用 Redis 缓存才导入 Redis 适配器,依赖 langchain_core 的对话记忆模型归属 `app.agent.memory`,文件缓存且未启用智能体的实例不再加载 redis 与 langchain_core。Telegram 渠道改用模块内 `app.modules.telegram.botapi` 精简 Bot API 客户端,经 `RequestUtils` 出站,宿主不再导入 pyTelegramBotAPI,启用 Telegram 的实例也不会因该 SDK 加载 redis;该依赖暂时保留给插件使用。Web Push 协议(aes128gcm 加密、VAPID 签名与经 `RequestUtils` 投递)由网络适配器 `app.adapters.network.webpush` 直接基于 http-ece 与 py-vapid 实现,消息端点与 `WebPushModule` 共用,宿主不再导入 pywebpush 及其连带的 aiohttp;该依赖同样暂时保留给插件使用。飞书渠道改用模块内 `app.modules.feishu.openapi` OpenAPI 客户端(经 `RequestUtils` 出站)与网络适配器 `app.adapters.network.feishu` 事件长连接(websocket-client 同步收发 pbbp2 帧),宿主不再导入 lark-oapi 及其上万个生成模块,长连接也不再依赖 SDK 的模块级事件循环;插件经 `app.sdk.feishu` 复用同一长连接,lark-oapi 暂时保留给尚未迁移的插件使用。API 文档路由由 `app.adapters.web.docs` 按 `API_DOCS_ENABLE` 逐请求开放,默认关闭,未开放时不生成文档。当前 `app.startup.lifecycle` 为 582、`app.factory` 为 595、`app.main` 为 597。音乐调用观察 `app.application.music.observation` 新增一个轻量模块,记录来源结果及请求预算;AcoustID及路径识别复用此上下文传递有界指纹候选,保留旧单ID模块合同。站点图片域名快照新增 `app.application.security.image`,各启动入口增加一个模块;性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。 架构专项验证分为两个 CI 投影:`Check event semantic policy` 先运行依赖、Adapter、出口和 Event 语义门禁,`Check host architecture snapshot` 再执行快照测试及一次 diff --git a/docs/refactor/optimization-checklist.md b/docs/refactor/optimization-checklist.md index cddd2fded..f162fa24a 100644 --- a/docs/refactor/optimization-checklist.md +++ b/docs/refactor/optimization-checklist.md @@ -98,7 +98,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁 | 指标 | 当前值 | 解释 | |---|---:|---| -| 宿主 Python 模块 / 内部依赖边 | 1114 / 9,429 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条合法模块导入边,资源过滤动作复用同一还原再新增 6 条;LLM 独占连接关闭复用宿主线程池;歌词字形转换复用 `app.foundation.text`;订阅创建使用 `app.domain.context.MediaInfo` 和运行时配置端口,将非 TMDB 影视身份投影为 TMDB 身份 | +| 宿主 Python 模块 / 内部依赖边 | 1114 / 9,430 | `dependency-baseline.json` 当前快照;种子失败冷却复用 `app.domain.torrent` 的限流语义,新增 1 条合法导入边;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条合法模块导入边,资源过滤动作复用同一还原再新增 6 条;LLM 独占连接关闭复用宿主线程池;歌词字形转换复用 `app.foundation.text`;订阅创建使用 `app.domain.context.MediaInfo` 和运行时配置端口,将非 TMDB 影视身份投影为 TMDB 身份 | | 非平凡 SCC | 1 | 仅保留精确 containment 的 29 模块 TMDB 移植包环 | | 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 | | Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 | diff --git a/docs/testing.md b/docs/testing.md index 140d7e36e..4910d6258 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -103,9 +103,14 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)): 种子下载重试的离线边界见 `tests/test_torrent_download_retry.py`:普通 GET 在网络失败、 403/5xx、空响应或无法解析的响应后最多重试两次,退避为 1、2 秒。签名链接刷新、换票地址、 -首次下载确认 POST 和 429 流控保持各自的既有流程。测试替换 HTTP 端口与等待,不访问真实站点。 +首次下载确认 POST 保持既有流程。HTTP 429 或 JSON `message` / `msg` 明确提示限流时, +停止短退避重试并在通知中保留原因,不把限流响应交给种子解析器或写入无效地址缓存。 +测试替换 HTTP 端口与等待,不访问真实站点。 瞬时状态不会写入 24 小时无效链接缓存;订阅记录的泛化“下载种子内容为空”使用 1 小时冷却, -明确资源失效仍保留 24 小时冷却。此策略不追溯修改已经写入的失败记录。 +明确资源失效仍保留 24 小时冷却。每日下载配额耗尽冷却 24 小时,覆盖站点时区差异; +短期限流至少冷却 1 小时,提示等待更长时按提示延长。准备流程通过单次失败回调把限流原因 +交给持久化冷却,避免统一的空内容错误覆盖它;签名链接遇到明确限流也不刷新重试。 +此策略不追溯修改已经写入的失败记录。 ## 自隔离:用了什么,就还原什么 diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index ff55d120c..7f3d91477 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -941,8 +941,8 @@ "runtime_only": true } }, - "edge_count": 9429, - "edge_sha256": "b2eb1e75f7e59ea3556fdeeced2155adfd619f2a3d3965cc1e2a4d643e4e1c4e", + "edge_count": 9430, + "edge_sha256": "e2e7ef5284db0d923080a54cb3ff25d5cca80e571324786576a432e4b6b6bcd4", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -4553,6 +4553,7 @@ "app.chain.download.failure -> app.domain.episode", "app.chain.download.failure -> app.domain.meta", "app.chain.download.failure -> app.domain.meta.metabase", + "app.chain.download.failure -> app.domain.torrent", "app.chain.download.failure -> app.runtime", "app.chain.download.failure -> app.runtime.log", "app.chain.download.failure -> app.schemas", diff --git a/tests/test_torrent_download_retry.py b/tests/test_torrent_download_retry.py index 2c0304526..29119d452 100644 --- a/tests/test_torrent_download_retry.py +++ b/tests/test_torrent_download_retry.py @@ -1,12 +1,20 @@ """种子 GET 的有界重试、缓存与冷却策略离线回归。""" +import json +from datetime import datetime +from pathlib import Path from unittest.mock import Mock import pytest from requests import Response import app.application.torrent.download as download +import app.chain.download.submission as submission +from app.chain.download import DownloadChain from app.chain.download.failure import DownloadFailureOwner +from app.domain.context import Context, MediaInfo, TorrentInfo +from app.domain.metainfo import MetaInfo +from app.schemas.types import MediaType URL = "https://tracker.example/download.php?id=39" CONTENT = b"d4:infod4:name10:Series.mkv6:lengthi1eee" @@ -174,3 +182,103 @@ def test_valid_cache_bypasses_network(boundary): def test_generic_empty_download_is_transient(error, ttl): """空内容不证明资源失效;明确文件损坏或删除继续按一天冷却。""" assert DownloadFailureOwner._download_failure_ttl(error) == ttl + + +@pytest.mark.parametrize("message,ttl", [ + ("相同種子當天最多下載10次", 86400), + ("相同种子当天最多下载10次", 86400), + ("当前请求太多,请10秒后重试", 3600), + ("請求過於頻繁,請2小時後重試", 7200), + ("Too many requests, retry after 90 minutes", 5400), +]) +@pytest.mark.parametrize("status", [200, 403, 429]) +@pytest.mark.parametrize("field", ["message", "msg"]) +def test_rate_limit_json_preserves_reason_without_retry(boundary, message, ttl, status, field): + """站点明确限流优先于 HTTP 状态,不解析为种子、不重试或污染无效地址缓存。""" + helper, port, cache, sleep = boundary + port.request.return_value = _response(status, json.dumps({"code": "1", field: message}, ensure_ascii=False).encode()) + parser = Mock(wraps=helper.get_fileinfo_from_torrent_content) + helper.get_fileinfo_from_torrent_content = parser + + result = helper.download_torrent(URL) + + assert result[1] is None + assert result[4] == f"站点限流:{message}" + assert DownloadFailureOwner._download_failure_ttl(result[4]) == ttl + port.request.assert_called_once() + sleep.assert_not_called() + parser.assert_not_called() + cache.set.assert_not_called() + helper.add_invalid.assert_not_called() + + +@pytest.mark.parametrize("content", [ + b'{"message":"torrent not found"}', b'{"message":"SUCCESS"}', + b'{"message":10}', b'{"message":{"error":"too many requests"}}', + b'{"message":"too many requests"', b'["too many requests"]', +]) +def test_other_json_does_not_become_rate_limit(boundary, content): + """无关错误、非文本字段和截断 JSON 保留原有恢复预算。""" + helper, port, _, sleep = boundary + port.request.side_effect = [_response(content=content), _response()] + assert helper.download_torrent(URL)[1] == CONTENT + assert port.request.call_count == 2 + sleep.assert_called_once_with(1) + + +def test_rate_limit_at_redirect_destination_is_not_retried(boundary): + """重定向落地返回配额错误时停止请求,不能继续消耗下载次数。""" + helper, port, _, sleep = boundary + redirect = _response(302) + redirect.headers["Location"] = "https://tracker.example/file.torrent" + message = "相同種子當天最多下載10次" + port.request.side_effect = [redirect, _response(content=json.dumps({"message": message}).encode())] + assert helper.download_torrent(URL)[4] == f"站点限流:{message}" + assert port.request.call_count == 2 + sleep.assert_not_called() + + +@pytest.mark.parametrize("link_type", ["ordinary", "signed", "indirect"]) +def test_daily_quota_reaches_notification_and_persisted_cooldown(boundary, monkeypatch, link_type): + """真实准备流程保留限流原因到通知和冷却记录,签名与换票也不得刷新重试。""" + _, port, cache, sleep = boundary + message = "相同種子當天最多下載10次" + port.request.return_value = _response(content=json.dumps({"code": "1", "message": message}).encode()) + chain = object.__new__(DownloadChain) + chain.post_message = Mock() + chain.search_site_torrents = Mock() + chain.download_failure_repository = Mock() + chain._apply_resource_download_event = Mock(return_value=(None, None)) + chain._record_music_album_track_keys = Mock() + chain._resolve_media_download_dir = Mock(return_value=("local", Path("/downloads"), None)) + chain._resolve_indirect_download_url = Mock(return_value=URL) + enclosure = {"ordinary": URL, "signed": URL + "&t=1&sign=old", + "indirect": "[encoded]https://api.m-team.cc/api/torrent/genDlToken"}[link_type] + context = Context( + torrent_info=TorrentInfo(site=1, site_name="馒头", title="Series S01E39", + enclosure=enclosure), + media_info=MediaInfo(title="Series", type=MediaType.TV), meta_info=MetaInfo("Series S01E39"), + ) + media = Mock() + media.supplement_tmdb_info.return_value = context.media_info + monkeypatch.setattr(submission, "MediaChain", Mock(return_value=media)) + + prepared, error = chain._prepare_download_single( + context=context, torrent_file=None, torrent_content=None, episodes=None, + channel=None, source="Subscribe|1", downloader=None, save_path=None, + userid=None, username=None, + ) + + assert prepared is None + assert error == f"站点限流:{message}" + chain.download_failure_repository.record_failure.assert_called_once() + failure = chain.download_failure_repository.record_failure.call_args.args[0] + assert failure.error_message == error + assert (datetime.fromisoformat(failure.next_retry_at) + - datetime.fromisoformat(failure.failed_at)).total_seconds() == 86400 + chain.post_message.assert_called_once() + assert error in chain.post_message.call_args.args[0].text + chain.search_site_torrents.assert_not_called() + port.request.assert_called_once() + sleep.assert_not_called() + cache.set.assert_not_called() diff --git a/tests/test_torrent_link_refresh.py b/tests/test_torrent_link_refresh.py index 3a093c92d..4c929369e 100644 --- a/tests/test_torrent_link_refresh.py +++ b/tests/test_torrent_link_refresh.py @@ -279,7 +279,7 @@ def test_real_torrent_parse_and_cooldown_follow_final_attempt(monkeypatch, final content = b"d4:infod4:name10:Series.mkv6:lengthi1eee" port = Mock() port.request.side_effect = [ - SimpleNamespace(status_code=404), + SimpleNamespace(status_code=404, content=b""), SimpleNamespace(status_code=final_status, content=content), ] monkeypatch.setattr(torrent_download, "_require_torrent_port", Mock(return_value=port))