mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-28 15:13:00 +08:00
fix(subscribe): 修复资源冷却后的搜索空转和手动重试 (#7628)
Refs #7623 将候选下载冷却反馈给智能分页搜索,保留缺集和重试原因;重新识别成功后清除目标资源的普通下载失败保护,并区分安全的网络失败类别。 本地全量 22,649 passed、21 skipped;PR 必需 CI 全部通过。
This commit is contained in:
@@ -38,6 +38,9 @@ AsyncHttpRequestError = httpx2.RequestError
|
||||
# 资源等幂等下载调用方通过同一异常边界区分可重试故障,不持有原始 transport。
|
||||
HttpConnectionError = requests.exceptions.ConnectionError
|
||||
HttpTimeoutError = requests.exceptions.Timeout
|
||||
# 面向用户的连接诊断区分代理与 TLS 故障,调用方仍只依赖宿主网络异常边界。
|
||||
HttpProxyError = requests.exceptions.ProxyError
|
||||
HttpTlsError = requests.exceptions.SSLError
|
||||
HttpResponseError = requests.exceptions.HTTPError
|
||||
HttpStreamError = requests.exceptions.ChunkedEncodingError
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ from app.api.response import (
|
||||
)
|
||||
from app.application.configuration import get_api_runtime_config_snapshot
|
||||
from app.application.torrent.cache import TorrentCacheRecognitionService
|
||||
from app.chain.download import DownloadChain
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.torrents import TorrentsChain
|
||||
from app.foundation.crypto import HashUtils
|
||||
@@ -244,7 +245,9 @@ async def reidentify_cache(
|
||||
_: object = Depends(get_current_active_superuser_async),
|
||||
) -> _SchemaResponse[dict[str, Any]]:
|
||||
"""
|
||||
重新识别指定的种子
|
||||
重新识别指定的种子,成功保存后清除该资源的自动下载失败冷却以允许再次尝试。
|
||||
|
||||
本接口不提交下载、不绕过站点限流,其他资源及重复提交保护不受影响。
|
||||
|
||||
:param domain: 站点域名
|
||||
:param torrent_hash: 种子hash(使用title+description的md5)
|
||||
@@ -255,7 +258,9 @@ async def reidentify_cache(
|
||||
"""
|
||||
|
||||
try:
|
||||
service = TorrentCacheRecognitionService(TorrentsChain(), MediaChain())
|
||||
service = TorrentCacheRecognitionService(
|
||||
TorrentsChain(), MediaChain(), DownloadChain().async_clear_download_failure,
|
||||
)
|
||||
success, message, data = await service.execute(
|
||||
domain=domain,
|
||||
torrent_hash=torrent_hash,
|
||||
|
||||
@@ -96,3 +96,12 @@ class DownloadFailureRepository(Protocol):
|
||||
:param failure: 本次下载失败与下一次重试时间的稳定快照
|
||||
"""
|
||||
...
|
||||
|
||||
async def async_delete_by_fingerprints(self, fingerprints: list[str]) -> int:
|
||||
"""
|
||||
清除人工确认资源对应的失败冷却,不扩展到同媒体的其他种子。
|
||||
|
||||
:param fingerprints: 人工操作前后资源上下文的普通失败指纹;空列表不执行删除
|
||||
:return: 已提交删除的失败记录数量;记录不存在时返回 0
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -91,7 +91,7 @@ def restore_collection(values: dict[str, Any]) -> SearchCollection:
|
||||
params[name] = set(params.get(name, []))
|
||||
sources[key] = SearchSourceCursor(**params)
|
||||
return SearchCollection(set(values["targets"]), sources, set(values["settled"]), set(values["fallback"]),
|
||||
dict(values.get("released") or {}))
|
||||
dict(values.get("released") or {}), set(values.get("deferred") or []))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
@@ -114,6 +114,7 @@ class SubscriptionExecutionContext:
|
||||
:param source: 触发本轮执行的入口,例如手工搜索或自动调度
|
||||
:param refresh_sites: 本轮需要更新进度的站点摘要
|
||||
:param refresh_candidates: 刷新站点进度时累计的候选资源数
|
||||
:param result_message: 本轮正常结束的补充说明,例如候选下载冷却原因及最早重试时间
|
||||
"""
|
||||
|
||||
lease: SubscriptionExecutionLease
|
||||
@@ -130,6 +131,7 @@ class SubscriptionExecutionContext:
|
||||
source: str = "automatic"
|
||||
refresh_sites: tuple[dict[str, object], ...] = ()
|
||||
refresh_candidates: int = 0
|
||||
result_message: Optional[str] = None
|
||||
|
||||
def is_cancel_requested(self) -> bool:
|
||||
"""
|
||||
|
||||
@@ -173,7 +173,8 @@ def finish_returned_search_task(
|
||||
return subscription_id, "completed", "cancelled"
|
||||
queue.release_task(task_id=task_id, lease_token=lease_token, cancelled=True)
|
||||
return None, "cancelled", "cancelled"
|
||||
queue.finish_task(task_id=task_id, lease_token=lease_token, state="completed")
|
||||
queue.finish_task(task_id=task_id, lease_token=lease_token, state="completed",
|
||||
error=execution_context.result_message)
|
||||
return subscription_id, "completed", None
|
||||
|
||||
|
||||
|
||||
@@ -2,14 +2,18 @@
|
||||
种子缓存相关的应用用例。
|
||||
"""
|
||||
|
||||
import copy
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.domain.context import MediaInfo, MusicInfo
|
||||
from app.domain.context import Context, MediaInfo, MusicInfo
|
||||
from app.domain.media import is_music_media_source, normalize_music_type
|
||||
from app.domain.meta.metamusic import MetaMusic
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.foundation.crypto import HashUtils
|
||||
from app.runtime.cache import async_cache_mutation
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.schemas.types import MUSIC_ENTITY_RECORDING, MediaSource, MediaType, MusicTargetEntityType
|
||||
|
||||
|
||||
@@ -18,12 +22,18 @@ class TorrentCacheRecognitionService:
|
||||
执行种子缓存条目的媒体重新识别用例。
|
||||
"""
|
||||
|
||||
def __init__(self, torrents_chain: Any, media_chain: Any) -> None:
|
||||
def __init__(self, torrents_chain: Any, media_chain: Any,
|
||||
reset_download_failure: Optional[Callable[[list[Context]], Awaitable[None]]] = None) -> None:
|
||||
"""
|
||||
初始化缓存和媒体识别依赖。
|
||||
|
||||
:param torrents_chain: 提供缓存读取、分类与持久化的种子链
|
||||
:param media_chain: 执行元数据识别的媒体链
|
||||
:param reset_download_failure: 缓存成功保存且识别出媒体身份后,清除该资源的下载失败退避
|
||||
"""
|
||||
self.torrents_chain = torrents_chain
|
||||
self.media_chain = media_chain
|
||||
self.reset_download_failure = reset_download_failure
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
@@ -37,7 +47,8 @@ class TorrentCacheRecognitionService:
|
||||
重新识别缓存条目并持久化影视、音乐分离后的缓存。
|
||||
|
||||
返回值保持端点原有的成功标识、用户消息和响应数据三元组,便于旧插件
|
||||
继续消费原始 HTTP 响应结构。
|
||||
继续消费原始 HTTP 响应结构。成功识别并保存后只清除本资源的自动下载失败记录,
|
||||
不主动提交下载,也不影响其他资源和重复提交保护。
|
||||
"""
|
||||
cache_data = await self.torrents_chain.async_get_torrents()
|
||||
if domain not in cache_data:
|
||||
@@ -114,6 +125,8 @@ class TorrentCacheRecognitionService:
|
||||
)
|
||||
else:
|
||||
mediainfo.clear()
|
||||
media_source_value, recognized_id = resolve_media_identity(media=mediainfo)
|
||||
recognized = bool(media_source_value and recognized_id)
|
||||
async with async_cache_mutation("torrent-snapshots"):
|
||||
# 远端识别期间不占写锁;提交时重读当前快照,仅修改本次目标。
|
||||
latest = await self.torrents_chain.async_get_torrents()
|
||||
@@ -122,7 +135,13 @@ class TorrentCacheRecognitionService:
|
||||
== torrent_hash), None)
|
||||
if current is None:
|
||||
return False, "种子缓存已刷新,目标条目不存在", None
|
||||
original = copy.copy(current)
|
||||
current.meta_info = meta
|
||||
current.media_info = mediainfo
|
||||
current.match_source = str(media_source_value) if recognized else "unknown"
|
||||
current.candidate_recognized = recognized
|
||||
current.media_info_is_target = False
|
||||
current.media_recognize_fail_count = 0 if recognized else 1
|
||||
video_cache, music_cache = self.torrents_chain.split_cache_contexts(latest)
|
||||
video_file, music_file = self.torrents_chain.cache_files()
|
||||
# 同一个资源不会跨分类移动;只写其所属缓存,避免无关文件失败或部分提交。
|
||||
@@ -132,6 +151,12 @@ class TorrentCacheRecognitionService:
|
||||
await self.torrents_chain.async_save_cache(cache, filename, strict=True)
|
||||
except Exception:
|
||||
return False, "种子缓存保存失败,请稍后重试", None
|
||||
if recognized and self.reset_download_failure is not None:
|
||||
try:
|
||||
await self.reset_download_failure([original, current])
|
||||
except Exception as err:
|
||||
logger.error(f"重新识别后清除资源下载失败记录失败:{err}")
|
||||
return False, "重新识别已保存,但清除下载失败记录失败,请重试", None
|
||||
return True, "重新识别完成", {
|
||||
"media_name": mediainfo.title if mediainfo else "",
|
||||
"media_year": mediainfo.year if mediainfo else "",
|
||||
|
||||
@@ -29,13 +29,17 @@ from app.domain.metainfo import MetaInfo
|
||||
from app.foundation import text as text_tools
|
||||
from app.foundation.crypto import HashUtils
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.runtime.cache import FileCache, TTLCache
|
||||
from app.runtime.cache import AsyncTTLCache, FileCache, TTLCache
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.exception import RateLimitExceededException
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.schemas.types import MediaSource, MediaType, SystemConfigKey
|
||||
|
||||
_SIZE_UNIT = 1024 * 1024
|
||||
# 同步拦截与人工异步放行共用缓存区域、容量和以秒计的有效期。
|
||||
_INVALID_TORRENT_REGION = "invalid_torrents"
|
||||
_INVALID_TORRENT_MAXSIZE = 128
|
||||
_INVALID_TORRENT_TTL = 24 * 3600
|
||||
|
||||
def _is_transient_torrent_status(status: int) -> bool:
|
||||
"""
|
||||
@@ -62,6 +66,12 @@ class TorrentResponsePort(Protocol):
|
||||
reason: str
|
||||
|
||||
|
||||
class TorrentRequestError(RuntimeError):
|
||||
"""
|
||||
种子传输端口返回的安全网络诊断,不包含下载地址、Cookie 或代理凭据。
|
||||
"""
|
||||
|
||||
|
||||
def _torrent_magnet_link(response: Optional[TorrentResponsePort], url: str) -> Optional[str]:
|
||||
"""
|
||||
从最终跳转地址或响应正文提取磁力链接,GET 和首次下载确认共用该判断。
|
||||
@@ -130,6 +140,7 @@ class TorrentHttpPort(Protocol):
|
||||
:param allow_redirects: 是否跟随 HTTP 重定向,默认允许
|
||||
:param data: POST 表单字段;None 表示无表单数据
|
||||
:return: 供种子解析使用的响应;请求失败且没有响应时为 None
|
||||
:raises TorrentRequestError: 传输失败,错误文本仅包含可向用户展示的网络故障类别
|
||||
"""
|
||||
|
||||
|
||||
@@ -314,7 +325,8 @@ class TorrentHelper:
|
||||
"""
|
||||
初始化种子失败地址缓存
|
||||
"""
|
||||
self._invalid_torrents = TTLCache(region="invalid_torrents", maxsize=128, ttl=3600 * 24)
|
||||
self._invalid_torrents = TTLCache(region=_INVALID_TORRENT_REGION,
|
||||
maxsize=_INVALID_TORRENT_MAXSIZE, ttl=_INVALID_TORRENT_TTL)
|
||||
|
||||
@staticmethod
|
||||
def _request_torrent(http_port: TorrentHttpPort, site: Mapping[str, Any],
|
||||
@@ -334,9 +346,15 @@ class TorrentHelper:
|
||||
普通种子 GET 瞬时失败时退避 1、2 秒;签名换票和确认 POST 不在此重试。
|
||||
"""
|
||||
for attempt in range(3 if retry else 1):
|
||||
response = self._request_torrent(http_port, site, method="GET", **request_options)
|
||||
if not retry or attempt == 2 or not self._should_retry_torrent_response(response):
|
||||
return response
|
||||
try:
|
||||
response = self._request_torrent(http_port, site, method="GET", **request_options)
|
||||
except TorrentRequestError:
|
||||
# 最终一次向上交还原诊断;中间失败仍沿用既有瞬时重试预算。
|
||||
if not retry or attempt == 2:
|
||||
raise
|
||||
else:
|
||||
if not retry or attempt == 2 or not self._should_retry_torrent_response(response):
|
||||
return response
|
||||
logger.warning(f"种子下载遇到瞬时失败,将进行第 {attempt + 1} 次重试")
|
||||
time.sleep(attempt + 1)
|
||||
return None
|
||||
@@ -488,7 +506,7 @@ class TorrentHelper:
|
||||
http_port, url=url, cookie=cookie, ua=ua, referer=referer,
|
||||
proxies=config.proxy if proxy else None, retry=retry, site=site,
|
||||
)
|
||||
except (ValueError, RateLimitExceededException) as err:
|
||||
except (ValueError, RateLimitExceededException, TorrentRequestError) as err:
|
||||
return cache_path, None, "", [], str(err)
|
||||
if magnet := _torrent_magnet_link(req, url):
|
||||
return cache_path if req is not None else None, magnet, "", [], "获取到磁力链接"
|
||||
@@ -517,7 +535,7 @@ class TorrentHelper:
|
||||
http_port, site=site, method="POST", url=action, cookie=cookie, ua=ua,
|
||||
referer=url, proxies=config.proxy if proxy else None, data=data, retry=retry,
|
||||
)
|
||||
except (ValueError, RateLimitExceededException) as err:
|
||||
except (ValueError, RateLimitExceededException, TorrentRequestError) as err:
|
||||
return cache_path, None, "", [], str(err)
|
||||
if magnet := _torrent_magnet_link(req, url):
|
||||
return cache_path if req is not None else None, magnet, "", [], "获取到磁力链接"
|
||||
@@ -772,6 +790,17 @@ class TorrentHelper:
|
||||
if url not in self._invalid_torrents:
|
||||
self._invalid_torrents[url] = True
|
||||
|
||||
async def async_remove_invalid(self, url: Optional[str]) -> None:
|
||||
"""
|
||||
人工确认资源后清除该下载地址的无效标记,其他地址的保护继续生效。
|
||||
|
||||
:param url: 本次人工操作对应的原始下载地址;为空或未被标记时不修改缓存
|
||||
"""
|
||||
if url:
|
||||
cache = AsyncTTLCache(region=_INVALID_TORRENT_REGION,
|
||||
maxsize=_INVALID_TORRENT_MAXSIZE, ttl=_INVALID_TORRENT_TTL)
|
||||
await cache.pop(url, False)
|
||||
|
||||
@staticmethod
|
||||
def match_torrent(
|
||||
mediainfo: MediaInfo,
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.application.download.failures import (
|
||||
DownloadFailureSnapshot,
|
||||
DownloadFailureWrite,
|
||||
)
|
||||
from app.application.torrent.download import TorrentHelper
|
||||
from app.chain.download.contract import _DownloadOwnerBase
|
||||
from app.domain import episode as episode_rules
|
||||
from app.domain import torrent as torrent_rules
|
||||
@@ -53,6 +54,23 @@ class DownloadFailureOwner(_DownloadOwnerBase):
|
||||
下载资源级失败与退避指纹、冷却和持久化 owner。
|
||||
"""
|
||||
|
||||
async def async_clear_download_failure(self, contexts: List[Context]) -> None:
|
||||
"""
|
||||
异步清除人工确认资源的失败台账和无效地址缓存,不清除重复提交的保护记录。
|
||||
|
||||
失败台账提交成功后才清除地址缓存。任何一步失败均向调用方报告,不把未完成的重试放行说成成功。
|
||||
|
||||
:param contexts: 操作前后同一资源的上下文;不接受按媒体或站点批量清除
|
||||
"""
|
||||
fingerprints = list(dict.fromkeys(fingerprint for context in contexts
|
||||
if (fingerprint := self._build_download_failure_fingerprint(context))))
|
||||
if fingerprints:
|
||||
await self.download_failure_repository.async_delete_by_fingerprints(fingerprints)
|
||||
helper = TorrentHelper()
|
||||
for context in contexts:
|
||||
if context.torrent_info is not None:
|
||||
await helper.async_remove_invalid(context.torrent_info.enclosure)
|
||||
|
||||
@staticmethod
|
||||
def _is_subscribe_source(source: Optional[str]) -> bool:
|
||||
"""
|
||||
|
||||
@@ -10,6 +10,7 @@ from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Callable, Optional, cast
|
||||
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.download.failures import DownloadFailureSnapshot
|
||||
from app.application.search.session import (
|
||||
SearchSessionRepository,
|
||||
SearchSessionSnapshot,
|
||||
@@ -232,6 +233,7 @@ class SearchScan:
|
||||
page_limit: Optional[int] = None,
|
||||
prefer_complete: bool = False,
|
||||
complete_scan: Optional[bool] = None,
|
||||
candidate_cooldowns: Optional[Callable[[list[Context]], dict[str, DownloadFailureSnapshot]]] = None,
|
||||
) -> None:
|
||||
"""
|
||||
创建或恢复一轮搜索,候选与匹配前史由检查点一起持有。
|
||||
@@ -239,6 +241,7 @@ class SearchScan:
|
||||
:param prefer_complete: 提交分集前先准备覆盖全部目标的候选;由订阅当前整包优先策略决定
|
||||
:param complete_scan: 是否翻完所有页再择优(用户选了完整搜索或洗版);否则各站第一页到齐就先提交,
|
||||
凑不齐的目标再继续翻页。未指定时跟随 full
|
||||
:param candidate_cooldowns: 按搜索资源键查询有效下载冷却;仅智能搜索据此暂缓目标的深页兜底
|
||||
"""
|
||||
if not isinstance(plan.mediainfo, MediaInfo):
|
||||
raise ValueError("分页影视搜索不适用于音乐")
|
||||
@@ -252,6 +255,7 @@ class SearchScan:
|
||||
not missing.episodes for seasons in (plan.no_exists or {}).values()
|
||||
for missing in seasons.values())))
|
||||
self.complete_scan = full if complete_scan is None else complete_scan
|
||||
self.candidate_cooldowns = candidate_cooldowns
|
||||
self.target_scope = target_scope
|
||||
self.page_limit = page_limit
|
||||
self.prefer_complete = prefer_complete
|
||||
@@ -277,6 +281,8 @@ class SearchScan:
|
||||
self.first_pass_done = False
|
||||
# 本轮因要等很久而先跳过的来源及其可再搜时间和原因;整轮什么都没交时改为等它们,不判搜索失败。
|
||||
self.long_waits: dict[str, tuple[str, str]] = {}
|
||||
# 暂缓目标的原因与最早重试时间随检查点保存,不能当成已提交或站点限流。
|
||||
self.cooldowns: dict[str, tuple[Optional[str], Optional[str]]] = {}
|
||||
self.sources = SearchSources(owner, plan)
|
||||
self._media_identity = encode_search_state({
|
||||
"source": self.media.media_source, "id": self.media.media_id, "type": self.media.type,
|
||||
@@ -357,6 +363,7 @@ class SearchScan:
|
||||
# 旧检查点没有这两项:按未先提交处理,升级后卡在整季屏障的任务能先交第一页已有的资源。
|
||||
self.first_pass_done = bool(data.get("first_pass_done", False))
|
||||
self.long_waits = {key: (value[0], value[1]) for key, value in data.get("long_waits", {}).items()}
|
||||
self.cooldowns = {key: (value[0], value[1]) for key, value in data.get("cooldowns", {}).items()}
|
||||
same_media = data["media_identity"] == self._media_identity
|
||||
if not same_media:
|
||||
self.restart = True
|
||||
@@ -410,7 +417,23 @@ class SearchScan:
|
||||
"retry": self.retry, "retry_reasons": self.retry_reasons,
|
||||
"recovery_failures": {key: count for key, count in self.recovery_failures.items() if key in candidates},
|
||||
"submitted": sorted(self.submitted), "first_pass_done": self.first_pass_done,
|
||||
"long_waits": self.long_waits, "saved_at": time.time()}
|
||||
"long_waits": self.long_waits, "cooldowns": self.cooldowns, "saved_at": time.time()}
|
||||
|
||||
def cooldown_text(self) -> str:
|
||||
"""
|
||||
汇总仍缺失且因下载冷却暂缓的目标,供日志及任务终态保留原因和最早重试时间。
|
||||
"""
|
||||
targets = self.collection.deferred & self.collection.remaining
|
||||
if not targets:
|
||||
return ""
|
||||
episodes = [int(target.split(":")[1]) for target in targets
|
||||
if ":" in target and target.split(":")[1].isdigit()]
|
||||
label = format_ranges(episodes) or ("影片" if self.media.type == MediaType.MOVIE else "整季")
|
||||
records = [self.cooldowns[target] for target in sorted(targets) if target in self.cooldowns]
|
||||
reasons = ";".join(dict.fromkeys(reason or "下载失败" for reason, _ in records))
|
||||
retry_at = min((retry for _, retry in records if retry), default=None)
|
||||
retry = f",最早 {retry_at} 后可重试" if retry_at else ""
|
||||
return f"{label} 的候选资源暂时跳过(原因:{reasons or '下载失败'}){retry}"
|
||||
|
||||
def progress_text(self) -> str:
|
||||
"""
|
||||
@@ -433,13 +456,14 @@ class SearchScan:
|
||||
waiting = "(站点上还没有,之后的定时检查会继续找)"
|
||||
else:
|
||||
waiting = f"(其中 {unreleased} 站点上还没有,之后的定时检查会继续找)"
|
||||
cooling = f"。{self.cooldown_text()}" if self.collection.deferred else ""
|
||||
if self.ended:
|
||||
skipped = sorted({self._site_name(key) for key, source in self.collection.sources.items()
|
||||
if source.failed and not key.startswith("plugin:")})
|
||||
note = f"。{('、'.join(skipped))} 这次没有搜成" if skipped else ""
|
||||
return f"搜索结束,{added}{missing}{waiting}{note}"
|
||||
return f"搜索结束,{added}{missing}{waiting}{note}{cooling}"
|
||||
page = max((source.next_page for source in self.collection.sources.values()), default=0)
|
||||
return f"已搜到第 {page} 页,{added}{missing}{waiting}"
|
||||
return f"已搜到第 {page} 页,{added}{missing}{waiting}{cooling}"
|
||||
|
||||
def _site_name(self, key: str) -> str:
|
||||
"""
|
||||
@@ -538,6 +562,10 @@ class SearchScan:
|
||||
self.retry.pop(key, None)
|
||||
self.retry_reasons.pop(key, None)
|
||||
self.live.update(contexts)
|
||||
# 其他缺集仍驱动分页时,新发现的替代资源应重新参与择源,不能继承旧候选的冷却结论。
|
||||
for candidate_id in contexts:
|
||||
if candidate_id not in self.attempted:
|
||||
self.collection.deferred.difference_update(self.identity[candidate_id]["targets"] or [])
|
||||
for candidate_id, context in contexts.items():
|
||||
self.candidates[candidate_id] = {"torrent": torrent_snapshot(context.torrent_info),
|
||||
"source": key, "page": page}
|
||||
@@ -744,6 +772,7 @@ class SearchScan:
|
||||
"""
|
||||
合集覆盖目标全就绪才提交;同轮已处理候选跨队列恢复不重试,剩余缓存先于共享游标兜底。
|
||||
"""
|
||||
ready = ready - self.collection.deferred
|
||||
contexts, keys = self._contexts(ready)
|
||||
contexts = self._filter(contexts)
|
||||
accepted = {
|
||||
@@ -763,9 +792,52 @@ class SearchScan:
|
||||
self.collection.settle(settled)
|
||||
cached = {target for key, record in self.identity.items() if key in self.candidates and key not in self.attempted
|
||||
for target in record["targets"] or []} & ready
|
||||
self._defer_cooling_targets(batch, ready - settled - cached)
|
||||
self.collection.deepen(ready - settled - cached)
|
||||
self.checkpoint()
|
||||
|
||||
def _defer_cooling_targets(self, batch: list[Context], targets: set[str]) -> None:
|
||||
"""
|
||||
智能模式在已收集候选全冷却时暂缓该目标;无退避事实的失败仍继续寻找替代资源。
|
||||
|
||||
:param batch: 刚交给下载层处理的候选,冷却查询须包含本次新记录的失败
|
||||
:param targets: 尚未成功提交且没有待处理缓存候选的目标
|
||||
"""
|
||||
if self.complete_scan or self.candidate_cooldowns is None or not batch or not targets:
|
||||
return
|
||||
records = self.candidate_cooldowns(batch)
|
||||
for target in targets:
|
||||
covering = [cast(str, item.torrent_info.search_resource_id) for item in batch
|
||||
if item.torrent_info is not None
|
||||
and target in self._coverage(cast(str, item.torrent_info.search_resource_id))]
|
||||
if not covering or any(key not in records for key in covering):
|
||||
continue
|
||||
first = min((records[key] for key in covering), key=lambda item: item.next_retry_at or "")
|
||||
self.collection.deferred.add(target)
|
||||
self.cooldowns[target] = (first.error_message, first.next_retry_at)
|
||||
if self.collection.deferred & targets:
|
||||
logger.info(f"{self.media.title_year} {self.cooldown_text()},本轮不再为这些目标翻页")
|
||||
|
||||
def _refresh_deferred_targets(self) -> None:
|
||||
"""
|
||||
恢复检查点时复核退避;到期或手工清除后只重新放行对应目标及其候选。
|
||||
"""
|
||||
deferred = self.collection.deferred & self.collection.remaining
|
||||
if not deferred:
|
||||
return
|
||||
contexts = [context for key in self.candidates if self._coverage(key) & deferred
|
||||
and (context := self._candidate_context(key)) is not None]
|
||||
records = self.candidate_cooldowns(contexts) if self.candidate_cooldowns else {}
|
||||
for target in deferred:
|
||||
covering = [cast(str, item.torrent_info.search_resource_id) for item in contexts
|
||||
if item.torrent_info is not None
|
||||
and target in self._coverage(cast(str, item.torrent_info.search_resource_id))]
|
||||
if covering and all(key in records for key in covering):
|
||||
continue
|
||||
self.collection.deferred.discard(target)
|
||||
self.cooldowns.pop(target, None)
|
||||
self.attempted.difference_update(key for key in self.candidates if target in self._coverage(key))
|
||||
|
||||
def _covered_targets(self) -> set[str]:
|
||||
"""
|
||||
未尝试候选仍覆盖的未提交目标,供第一页先交和站点未收录早停判断使用。
|
||||
@@ -809,6 +881,7 @@ class SearchScan:
|
||||
self.recovery_failures = {}
|
||||
self.first_pass_done = False
|
||||
self.long_waits = {}
|
||||
self.cooldowns = {}
|
||||
self.sources.queries = {}
|
||||
self.sources.keyword_index = 0
|
||||
self.attempted.clear()
|
||||
@@ -895,7 +968,7 @@ class SearchScan:
|
||||
|
||||
:return: 已把等待中的来源放回重试队列时为 True,调用方继续循环并按重试时间交还队列
|
||||
"""
|
||||
if self.submitted or not self.long_waits or not self.collection.remaining:
|
||||
if self.submitted or not self.long_waits or not (self.collection.remaining - self.collection.deferred):
|
||||
return False
|
||||
for key, (retry_at, reason) in self.long_waits.items():
|
||||
source = self.collection.sources[key]
|
||||
@@ -928,6 +1001,7 @@ class SearchScan:
|
||||
started = time.monotonic()
|
||||
if self.restart:
|
||||
self._reset_changed_contract()
|
||||
self._refresh_deferred_targets()
|
||||
while self.collection.remaining:
|
||||
if self._stopping():
|
||||
return
|
||||
@@ -937,7 +1011,8 @@ class SearchScan:
|
||||
if self._has_cached_ready() or self.collection.active_sources(full=self.full):
|
||||
continue
|
||||
# 智能模式只剩站点未收录目标时不再尝试别名;完整模式仍保留别名的深页收集机会。
|
||||
if not (self.full or self.collection.pending) or not self._add_sources():
|
||||
if (not (self.collection.remaining - self.collection.deferred)
|
||||
or not (self.full or self.collection.pending) or not self._add_sources()):
|
||||
if self._wait_for_long_waits():
|
||||
continue
|
||||
self._finish_round()
|
||||
|
||||
@@ -302,6 +302,42 @@ def _prepare_subscription_match(
|
||||
return meta, mediainfo, routed_torrents, domains, sub_sites
|
||||
|
||||
|
||||
def _recognition_candidates(
|
||||
torrents: Dict[str, List[Context]], subscribes: list[SubscriptionSnapshot],
|
||||
) -> Dict[str, List[Context]]:
|
||||
"""
|
||||
外部重识别前按当前订阅的明确类型和标题季号裁剪未知身份候选。
|
||||
|
||||
自定义识别词可能改变类型和季号,因此保留完整候选;未知类型、未标季、别名和年份差异
|
||||
同样保留。已经识别出的身份仍交给原有索引及严格匹配处理,不能用预筛替代身份复核。
|
||||
|
||||
:param torrents: 按站点组织的共享资源,不修改输入及候选本身
|
||||
:param subscribes: 本轮实际需要匹配的活动订阅
|
||||
:return: 仍可能被当前订阅使用的候选,保持原站点及资源顺序
|
||||
"""
|
||||
if not subscribes:
|
||||
return {}
|
||||
if any(subscribe.custom_words for subscribe in subscribes):
|
||||
return torrents
|
||||
scopes = {(CandidateIndex.normalize_media_type(subscribe.type), CandidateIndex.normalize_int(subscribe.season))
|
||||
for subscribe in subscribes}
|
||||
selected: Dict[str, List[Context]] = {}
|
||||
for domain, contexts in torrents.items():
|
||||
selected[domain] = []
|
||||
for context in contexts:
|
||||
meta = getattr(context, "meta_info", None)
|
||||
media = getattr(context, "media_info", None)
|
||||
if meta is None or (media and resolve_media_identity(media=media)[1]):
|
||||
selected[domain].append(context)
|
||||
continue
|
||||
media_type = CandidateIndex.normalize_media_type(getattr(meta, "type", None))
|
||||
seasons = CandidateIndex.meta_seasons(meta)
|
||||
if any((not media_type or not target_type or media_type == target_type)
|
||||
and (not seasons or season is None or season in seasons) for target_type, season in scopes):
|
||||
selected[domain].append(context)
|
||||
return selected
|
||||
|
||||
|
||||
def _prepare_match_torrents(
|
||||
torrents: Dict[str, List[Context]],
|
||||
) -> Dict[str, List[Context]]:
|
||||
@@ -443,12 +479,11 @@ class SubscribeMatchOwner(_SubscribeOwnerBase):
|
||||
if not lock_acquired:
|
||||
return
|
||||
|
||||
processed_torrents = self._prepare_match_torrents(torrents)
|
||||
candidate_index, fresh_fact_lease = CandidateIndex(processed_torrents), FreshFactLease()
|
||||
|
||||
subscribes = self.subscription_repository.list(self.get_states_for_search("R"))
|
||||
if mtype is not None:
|
||||
subscribes = [subscribe for subscribe in subscribes if subscribe.type == mtype]
|
||||
processed_torrents = self._prepare_match_torrents(_recognition_candidates(torrents, subscribes))
|
||||
candidate_index, fresh_fact_lease = CandidateIndex(processed_torrents), FreshFactLease()
|
||||
total_num = len(subscribes)
|
||||
summary.total = total_num
|
||||
logger.info(summary.start_log())
|
||||
|
||||
@@ -12,6 +12,7 @@ from typing import Any, Callable, Optional, cast
|
||||
from uuid import uuid4
|
||||
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.download.failures import DownloadFailureSnapshot
|
||||
from app.application.download.pending import (
|
||||
pending_blocks_movie_music,
|
||||
pending_targets_for_scan,
|
||||
@@ -256,6 +257,33 @@ def _paused_pending_targets(
|
||||
return paused & ready
|
||||
|
||||
|
||||
def _subscription_candidate_cooldowns(
|
||||
download_chain: DownloadChain,
|
||||
subscribe: SubscriptionSnapshot,
|
||||
source: str,
|
||||
contexts: list[Context],
|
||||
) -> dict[str, DownloadFailureSnapshot]:
|
||||
"""
|
||||
把资源下载退避映射为当前分页候选键,保持下载器及订阅范围与真实择源一致。
|
||||
|
||||
:param download_chain: 读取下载失败台账的下载链
|
||||
:param subscribe: 本轮订阅快照,使用其下载器配置隔离退避范围
|
||||
:param source: 与批量下载相同的订阅来源标识
|
||||
:param contexts: 本批已经参与择源的资源
|
||||
:return: 仍在下载退避期的搜索资源键及失败快照
|
||||
"""
|
||||
records = download_chain._active_download_failure_fingerprints(
|
||||
contexts=contexts, source=source, downloader=subscribe.downloader,
|
||||
)
|
||||
result: dict[str, DownloadFailureSnapshot] = {}
|
||||
for context in contexts:
|
||||
torrent = context.torrent_info
|
||||
fingerprint = download_chain._build_download_failure_fingerprint(context)
|
||||
if torrent is not None and torrent.search_resource_id and fingerprint and fingerprint in records:
|
||||
result[torrent.search_resource_id] = records[fingerprint]
|
||||
return result
|
||||
|
||||
|
||||
def _process_paged_subscription(owner: _SubscribeOwnerBase, subscribe: SubscriptionSnapshot,
|
||||
searchchain: SearchChain, target: SubscriptionSearchTarget,
|
||||
rule_key: SystemConfigKey,
|
||||
@@ -304,7 +332,9 @@ def _process_paged_subscription(owner: _SubscribeOwnerBase, subscribe: Subscript
|
||||
page_limit=1 if strategy == "single_page" else None,
|
||||
execution=execution_context, repository=repository, snapshot=snapshot,
|
||||
target_scope=(subscribe.start_episode or 1, subscribe.total_episode or 0),
|
||||
prefer_complete=prefer_initial_pack, complete_scan=strategy == "full")
|
||||
prefer_complete=prefer_initial_pack, complete_scan=strategy == "full",
|
||||
candidate_cooldowns=partial(_subscription_candidate_cooldowns, download_chain, subscribe,
|
||||
owner.get_subscribe_source_keyword(subscribe)))
|
||||
if execution_context:
|
||||
execution_context.incremental_search = True
|
||||
|
||||
@@ -345,6 +375,7 @@ def _process_paged_subscription(owner: _SubscribeOwnerBase, subscribe: Subscript
|
||||
_finish_paged_subscription(owner, subscribe, target)
|
||||
if execution_context:
|
||||
execution_context.scan_finished = not execution_context.should_stop() and not runtime_stop_state.is_system_stopped
|
||||
execution_context.result_message = scan.cooldown_text() or None
|
||||
execution_context.report_phase("finished")
|
||||
return cast(Optional[SubscriptionSnapshot], owner.subscription_repository.get(subscribe.id))
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from types import MappingProxyType
|
||||
from typing import Any, Optional, TypeVar
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.application.download.failures import (
|
||||
@@ -21,7 +23,7 @@ from app.application.download.pending import (
|
||||
from app.db.models.downloadpending import DownloadPending
|
||||
from app.db.oper.downloadfailure import DownloadFailureOper
|
||||
from app.db.oper.downloadpending import DownloadPendingOper
|
||||
from app.db.uow import SqlAlchemyUnitOfWork
|
||||
from app.db.uow import SqlAlchemyAsyncUnitOfWork, SqlAlchemyUnitOfWork
|
||||
from app.schemas.media import normalize_media_source
|
||||
|
||||
_T = TypeVar("_T")
|
||||
@@ -93,11 +95,16 @@ class TransactionalDownloadFailureRepository:
|
||||
为 Chain 下载失败读写创建短生命周期会话并显式收口事务。
|
||||
"""
|
||||
|
||||
def __init__(self, session_factory: Callable[[], Session]) -> None:
|
||||
def __init__(self, session_factory: Callable[[], Session],
|
||||
async_session_factory: Optional[Callable[[], AbstractAsyncContextManager[AsyncSession]]] = None) -> None:
|
||||
"""
|
||||
保存由启动组合根提供的同步会话工厂。
|
||||
保存由启动组合根提供的同步与可选异步短会话工厂。
|
||||
|
||||
:param session_factory: 同步择源使用的独立数据库会话工厂
|
||||
:param async_session_factory: 人工重试清理使用的异步会话工厂;未装配时拒绝异步删除
|
||||
"""
|
||||
self._session_factory = session_factory
|
||||
self._async_session_factory = async_session_factory
|
||||
|
||||
def get_active_by_fingerprints(
|
||||
self,
|
||||
@@ -154,6 +161,28 @@ class TransactionalDownloadFailureRepository:
|
||||
raise
|
||||
|
||||
|
||||
async def async_delete_by_fingerprints(self, fingerprints: list[str]) -> int:
|
||||
"""
|
||||
以短事务清除人工确认资源的失败冷却,提交失败时保留原记录并向调用方报告。
|
||||
|
||||
:param fingerprints: 需要清除的普通资源失败指纹
|
||||
:return: 已成功提交删除的记录数
|
||||
"""
|
||||
if self._async_session_factory is None:
|
||||
raise RuntimeError("下载失败清理异步会话尚未装配")
|
||||
async with self._async_session_factory() as session:
|
||||
transaction = SqlAlchemyAsyncUnitOfWork(session)
|
||||
try:
|
||||
count: int = await session.run_sync(
|
||||
lambda sync_session: DownloadFailureOper(db=sync_session).delete_by_fingerprints(fingerprints)
|
||||
)
|
||||
await transaction.commit()
|
||||
return count
|
||||
except Exception:
|
||||
await transaction.rollback()
|
||||
raise
|
||||
|
||||
|
||||
class TransactionalDownloadPendingRepository:
|
||||
"""
|
||||
为 Chain 待确认下载状态读写创建短生命周期会话并显式收口事务。
|
||||
|
||||
@@ -119,6 +119,23 @@ class DownloadFailure(Base):
|
||||
db.add(failure)
|
||||
return failure
|
||||
|
||||
@classmethod
|
||||
def delete_by_fingerprints(cls, db: Session, fingerprints: List[str]) -> int:
|
||||
"""
|
||||
在调用方事务中删除明确指定的资源失败记录,不影响其他资源或重复提交退避。
|
||||
|
||||
:param db: 由调用方持有并负责提交的会话
|
||||
:param fingerprints: 待清除的完整资源指纹;空列表不执行删除
|
||||
:return: 实际删除的记录数
|
||||
"""
|
||||
normalized = list(dict.fromkeys(fingerprint for fingerprint in fingerprints if fingerprint))
|
||||
if not normalized:
|
||||
return 0
|
||||
return execute_dml(
|
||||
db, delete(cls).where(cls.fingerprint.in_(normalized)),
|
||||
execution_options={"synchronize_session": False},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def delete_expired(
|
||||
cls,
|
||||
|
||||
@@ -54,6 +54,17 @@ class DownloadFailureOper(DbOper):
|
||||
)
|
||||
)
|
||||
|
||||
def delete_by_fingerprints(self, fingerprints: List[str]) -> int:
|
||||
"""
|
||||
暂存人工确认资源的失败冷却删除,事务仍由调用方拥有。
|
||||
|
||||
:param fingerprints: 需要清除的普通资源失败指纹
|
||||
:return: 删除的记录数;空列表或记录不存在时为 0
|
||||
"""
|
||||
return self._execute_sync_write(
|
||||
lambda session: DownloadFailure.delete_by_fingerprints(session, fingerprints)
|
||||
)
|
||||
|
||||
def delete_expired(
|
||||
self,
|
||||
before_time: str,
|
||||
|
||||
@@ -181,6 +181,7 @@ class SearchCollection:
|
||||
:param settled: 已成功提交或确认已存在的目标
|
||||
:param fallback: 需要从当前进度继续完整搜索的目标
|
||||
:param released: 本轮任一来源出现过的本作品各季最大集号,键为季号字符串
|
||||
:param deferred: 本轮因可用候选全部处于下载冷却而暂缓的目标,仍计入缺失内容
|
||||
"""
|
||||
|
||||
targets: set[str]
|
||||
@@ -188,6 +189,7 @@ class SearchCollection:
|
||||
settled: set[str] = field(default_factory=set)
|
||||
fallback: set[str] = field(default_factory=set)
|
||||
released: dict[str, int] = field(default_factory=dict)
|
||||
deferred: set[str] = field(default_factory=set)
|
||||
|
||||
@property
|
||||
def remaining(self) -> set[str]:
|
||||
@@ -239,7 +241,7 @@ class SearchCollection:
|
||||
return set()
|
||||
unreleased = set() if full else self.unreleased()
|
||||
return {
|
||||
target for target in self.remaining
|
||||
target for target in self.remaining - self.deferred
|
||||
if all(
|
||||
source.exhausted or source.failed or source.limit_reached
|
||||
or (target in unreleased and source.next_page > 0)
|
||||
@@ -252,17 +254,18 @@ class SearchCollection:
|
||||
"""
|
||||
完整模式由所有未满足目标驱动分页,智能模式才按站点已见集号裁剪目标。
|
||||
"""
|
||||
driving = self.remaining if full else self.remaining - self.unreleased()
|
||||
fallback = driving if full else self.fallback
|
||||
searchable = self.remaining - self.deferred
|
||||
driving = searchable if full else searchable - self.unreleased()
|
||||
fallback = driving if full else self.fallback - self.deferred
|
||||
return [key for key, source in self.sources.items()
|
||||
if source.drives_search(driving if source.next_page else self.remaining, fallback)]
|
||||
if source.drives_search(driving if source.next_page else searchable, fallback)]
|
||||
|
||||
@property
|
||||
def pending(self) -> set[str]:
|
||||
"""
|
||||
仍值得在本轮继续寻找的目标;只剩站点未收录目标时本轮结束并释放检查点。
|
||||
"""
|
||||
return self.remaining - self.unreleased()
|
||||
return self.remaining - self.unreleased() - self.deferred
|
||||
|
||||
def settle(self, targets: set[str]) -> None:
|
||||
"""
|
||||
@@ -270,6 +273,7 @@ class SearchCollection:
|
||||
"""
|
||||
self.settled.update(targets & self.targets)
|
||||
self.fallback.difference_update(targets)
|
||||
self.deferred.difference_update(targets)
|
||||
|
||||
def deepen(self, targets: set[str]) -> None:
|
||||
"""
|
||||
|
||||
@@ -139,7 +139,7 @@ def build_chain_runtime_context(
|
||||
transfer_admission_repository=TransactionalTransferAdmissionRepository(SessionFactory),
|
||||
transfer_execution_repository=dependencies.transfer_execution,
|
||||
media_server_repository=TransactionalMediaServerRepository(SessionFactory),
|
||||
download_failure_repository=TransactionalDownloadFailureRepository(SessionFactory),
|
||||
download_failure_repository=TransactionalDownloadFailureRepository(SessionFactory, async_session_scope),
|
||||
download_pending_repository=TransactionalDownloadPendingRepository(SessionFactory),
|
||||
user_repository=build_transactional_user_repository(),
|
||||
classification_service=classification_service,
|
||||
|
||||
@@ -10,7 +10,14 @@ from app.adapters.external.cookiecloud import CookieCloudHelper
|
||||
from app.adapters.external.ocr import OcrHelper
|
||||
from app.adapters.network.browser import PlaywrightHelper
|
||||
from app.adapters.network.cloudflare import under_challenge
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.adapters.network.http import (
|
||||
HttpConnectionError,
|
||||
HttpProxyError,
|
||||
HttpRequestError,
|
||||
HttpTimeoutError,
|
||||
HttpTlsError,
|
||||
RequestUtils,
|
||||
)
|
||||
from app.adapters.system import rust as rust_accel
|
||||
from app.application.module import get_module_manager
|
||||
from app.application.rss import (
|
||||
@@ -41,6 +48,7 @@ from app.application.site.protocol import (
|
||||
)
|
||||
from app.application.torrent.download import (
|
||||
TorrentHttpPort,
|
||||
TorrentRequestError,
|
||||
TorrentResponsePort,
|
||||
configure_torrent_port,
|
||||
reset_torrent_port,
|
||||
@@ -426,7 +434,9 @@ class _TorrentHttpAdapter:
|
||||
allow_redirects: bool = True,
|
||||
data: Optional[dict[str, Any]] = None) -> Optional[TorrentResponsePort]:
|
||||
"""
|
||||
按 Application 指定方法发起请求并保留响应三态。
|
||||
按 Application 指定方法发起请求,保留 HTTP 状态并把传输异常转换为不含凭据的故障类别。
|
||||
|
||||
:raises TorrentRequestError: 请求超时、代理、TLS 或连接失败;不转发可能包含敏感 URL 的原异常文本
|
||||
"""
|
||||
request = RequestUtils(
|
||||
ua=ua or "",
|
||||
@@ -434,12 +444,21 @@ class _TorrentHttpAdapter:
|
||||
referer=referer or "",
|
||||
proxies=proxies or {},
|
||||
)
|
||||
if method == "POST":
|
||||
response = request.post_res(
|
||||
url=url, data=data, allow_redirects=allow_redirects
|
||||
)
|
||||
else:
|
||||
response = request.get_res(url=url, allow_redirects=allow_redirects)
|
||||
try:
|
||||
if method == "POST":
|
||||
response = request.post_res(
|
||||
url=url, data=data, allow_redirects=allow_redirects, raise_exception=True,
|
||||
)
|
||||
else:
|
||||
response = request.get_res(url=url, allow_redirects=allow_redirects, raise_exception=True)
|
||||
except HttpRequestError as err:
|
||||
reason = next((label for kind, label in (
|
||||
(HttpProxyError, "代理连接失败,请检查站点代理配置"),
|
||||
(HttpTimeoutError, "请求超时"),
|
||||
(HttpTlsError, "TLS 连接失败"),
|
||||
(HttpConnectionError, "网络连接失败"),
|
||||
) if isinstance(err, kind)), "网络请求失败")
|
||||
raise TorrentRequestError(f"无法打开链接:{reason}") from None
|
||||
return cast(Optional[TorrentResponsePort], response)
|
||||
|
||||
|
||||
|
||||
@@ -851,7 +851,7 @@ flowchart LR
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1200 |
|
||||
| 内部导入边 | 10,679 |
|
||||
| 内部导入边 | 10,687 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) |
|
||||
|
||||
@@ -30,6 +30,19 @@
|
||||
Server 使用独立 SQL 表长期保存关系,不属于识别缓存清理范围。公共上报只补缺,
|
||||
管理后台可纠正目标或撤销错误关系;撤销保留记录,防止旧实例覆盖。实例正缓存最多一小时后更新。
|
||||
|
||||
### 种子重新识别与下载失败重试
|
||||
|
||||
管理员调用 `torrent.cache.reidentify`(`POST /api/v1/torrent/cache/reidentify/{domain}/{torrent_hash}`)
|
||||
成功识别并保存媒体身份后,会清除该资源在修正前后身份下的自动下载失败冷却和原下载地址的无效标记。
|
||||
该操作不会主动提交下载;随后可重新触发订阅搜索或手动下载,以重新检查链接。其他资源、下载器重复提交保护
|
||||
和站点限流不受影响。识别无结果、缓存保存失败或清理事务失败时,不清除失败保护;清理失败会明确返回失败。
|
||||
|
||||
智能订阅搜索中,同一目标已收集的合格候选全部处于下载冷却时,本轮不再为该目标继续深翻。
|
||||
缺集仍然保留,其他目标继续搜索;新页发现该目标的替代资源时重新参与择源。完整搜索保持深页查找策略。
|
||||
本轮正常结束后,`subscription.execution.get` / `subscription.execution.list` 返回终态与实际提交计数,
|
||||
并在现有 `error` 摘要中保留资源冷却原因和最早可重试时间,避免把资源冷却显示为等待站点配额。
|
||||
种子网络请求会保留 HTTP 状态,超时、代理、TLS 和连接故障以不含 URL 凭据的类别反馈。
|
||||
|
||||
### 外部整理历史登记
|
||||
|
||||
管理员可通过 `transfer.history.register`(`POST /api/v1/history/transfer`)登记已经完成的
|
||||
|
||||
@@ -18,7 +18,7 @@ if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
# 与对应 SKILL.md 同步维护,重新生成不能回退用户同步所需的版本。
|
||||
MOVIEPILOT_API_SKILL_VERSION = "79"
|
||||
MOVIEPILOT_API_SKILL_VERSION = "80"
|
||||
DATABASE_OPERATION_SKILL_VERSION = "20"
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: moviepilot-api
|
||||
version: 79
|
||||
version: 80
|
||||
description: >-
|
||||
Use this skill for MoviePilot product operations such as media search, torrent
|
||||
search, downloads, subscriptions, library checks, sites, storage, workflows,
|
||||
@@ -67,6 +67,16 @@ allowed-api-operations: >-
|
||||
|
||||
# MoviePilot API
|
||||
|
||||
`torrent.cache.reidentify` releases that resource's automatic download-failure
|
||||
cooldown and invalid-link marker only after recognition and cache persistence
|
||||
succeed. It does not submit a download or bypass site limits or duplicate-task
|
||||
protection. Retry with `subscription.search` or an explicit download afterward;
|
||||
if cleanup fails, inspect the returned error before claiming retry is available.
|
||||
Smart subscription search ends a target's deep fallback when all collected
|
||||
eligible candidates are cooling, while retaining missing episodes. Read the
|
||||
terminal execution state, submitted count, and `error` summary for the reason and
|
||||
earliest retry time; do not interpret a completed search as a completed download.
|
||||
|
||||
When a plugin mutation is busy or its outcome is unknown, inspect `plugin.runtime.status`
|
||||
before retrying. `active_operation` identifies the running plugin, operation, hook, and
|
||||
elapsed time. A caller timeout or cancellation does not stop the hook and must never
|
||||
|
||||
@@ -130,7 +130,7 @@ def test_modified_builtin_skills_have_incremented_versions() -> None:
|
||||
"database-operation": "20",
|
||||
"feedback-issue": "12",
|
||||
"anysearch": "3",
|
||||
"moviepilot-api": "79",
|
||||
"moviepilot-api": "80",
|
||||
"moviepilot-update": "7",
|
||||
"organize-files": "6",
|
||||
"transfer-failed-retry": "7",
|
||||
|
||||
@@ -561,7 +561,7 @@ def configure_plugin_system_services():
|
||||
transfer_admission_repository=TransactionalTransferAdmissionRepository(SessionFactory),
|
||||
transfer_execution_repository=TransactionalTransferExecutionRepository(SessionFactory),
|
||||
media_server_repository=TransactionalMediaServerRepository(SessionFactory),
|
||||
download_failure_repository=TransactionalDownloadFailureRepository(SessionFactory),
|
||||
download_failure_repository=TransactionalDownloadFailureRepository(SessionFactory, async_session_scope),
|
||||
download_pending_repository=TransactionalDownloadPendingRepository(SessionFactory),
|
||||
user_repository=user_repository(),
|
||||
configuration=build_chain_runtime_config(settings),
|
||||
|
||||
@@ -980,8 +980,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10679,
|
||||
"edge_sha256": "8598166523cd5e82081a70228ab927eed7db280339941daf3c0090443bb150fc",
|
||||
"edge_count": 10687,
|
||||
"edge_sha256": "5395c7542852c2c45dbcd0325f522e49ff7c0c62ca8f9054d53449b743b47ce4",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -3507,6 +3507,7 @@
|
||||
"app.api.endpoints.torrent -> app.application.torrent",
|
||||
"app.api.endpoints.torrent -> app.application.torrent.cache",
|
||||
"app.api.endpoints.torrent -> app.chain",
|
||||
"app.api.endpoints.torrent -> app.chain.download",
|
||||
"app.api.endpoints.torrent -> app.chain.media",
|
||||
"app.api.endpoints.torrent -> app.chain.torrents",
|
||||
"app.api.endpoints.torrent -> app.foundation",
|
||||
@@ -4738,7 +4739,9 @@
|
||||
"app.application.torrent.cache -> app.foundation.crypto",
|
||||
"app.application.torrent.cache -> app.runtime",
|
||||
"app.application.torrent.cache -> app.runtime.cache",
|
||||
"app.application.torrent.cache -> app.runtime.log",
|
||||
"app.application.torrent.cache -> app.schemas",
|
||||
"app.application.torrent.cache -> app.schemas.media",
|
||||
"app.application.torrent.cache -> app.schemas.types",
|
||||
"app.application.torrent.download -> app.application",
|
||||
"app.application.torrent.download -> app.application.configuration",
|
||||
@@ -5074,6 +5077,8 @@
|
||||
"app.chain.download.failure -> app.application",
|
||||
"app.chain.download.failure -> app.application.download",
|
||||
"app.chain.download.failure -> app.application.download.failures",
|
||||
"app.chain.download.failure -> app.application.torrent",
|
||||
"app.chain.download.failure -> app.application.torrent.download",
|
||||
"app.chain.download.failure -> app.chain",
|
||||
"app.chain.download.failure -> app.chain.download",
|
||||
"app.chain.download.failure -> app.chain.download.contract",
|
||||
@@ -5799,6 +5804,8 @@
|
||||
"app.chain.search.result -> app.schemas.types",
|
||||
"app.chain.search.scan -> app.application",
|
||||
"app.chain.search.scan -> app.application.configuration",
|
||||
"app.chain.search.scan -> app.application.download",
|
||||
"app.chain.search.scan -> app.application.download.failures",
|
||||
"app.chain.search.scan -> app.application.search",
|
||||
"app.chain.search.scan -> app.application.search.session",
|
||||
"app.chain.search.scan -> app.application.site",
|
||||
@@ -6236,6 +6243,7 @@
|
||||
"app.chain.subscribe.search -> app.application",
|
||||
"app.chain.subscribe.search -> app.application.configuration",
|
||||
"app.chain.subscribe.search -> app.application.download",
|
||||
"app.chain.subscribe.search -> app.application.download.failures",
|
||||
"app.chain.subscribe.search -> app.application.download.pending",
|
||||
"app.chain.subscribe.search -> app.application.mediaserver",
|
||||
"app.chain.subscribe.search -> app.application.subscription",
|
||||
|
||||
@@ -7,6 +7,7 @@ from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.download.failures import DownloadFailureSnapshot
|
||||
from app.application.search.session import SearchSessionSnapshot, encode_search_state
|
||||
from app.application.site.observation import SiteSearchObservation, report_site_search_outcome, report_site_search_page
|
||||
from app.application.subscription.sitebudget import (
|
||||
@@ -73,12 +74,126 @@ def unknown_torrent(page):
|
||||
enclosure=f"https://site.example/download?id=unknown-{page}")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("full,all_cooling", [(False, True), (False, False), (True, True)])
|
||||
def test_cooling_candidates_stop_smart_fallback_without_settling_missing(owner, monkeypatch, full, all_cooling):
|
||||
"""
|
||||
智能搜索不为全冷却目标深翻,完整搜索仍查后页;两者均不把退避当作下载成功。
|
||||
"""
|
||||
calls = pages(owner, monkeypatch, {0: [torrent(18, 1), torrent(18, 2)],
|
||||
1: [torrent(18, 3)]})
|
||||
submitted = []
|
||||
failure = DownloadFailureSnapshot("failure", "无法打开链接", "2026-11-27 19:30:00")
|
||||
|
||||
def cooldowns(items):
|
||||
"""
|
||||
只有首页两个版本仍在退避,深页版本可以正常尝试。
|
||||
"""
|
||||
return {item.torrent_info.search_resource_id: failure for item in items
|
||||
if item.torrent_info.description == "18-1"
|
||||
or (all_cooling and item.torrent_info.description == "18-2")}
|
||||
|
||||
scan = SearchScan(owner=owner, plan=plan(list(range(18, 35))), full=full,
|
||||
candidate_cooldowns=cooldowns)
|
||||
|
||||
def submit(items, _ready):
|
||||
"""
|
||||
记录实际择源批次,所有下载均未成功,缺集应保持不变。
|
||||
"""
|
||||
submitted.extend(item.torrent_info.description for item in items)
|
||||
return set()
|
||||
|
||||
scan.run(submit)
|
||||
|
||||
deepen = full or not all_cooling
|
||||
assert calls == ([0, 1, 2] if deepen else [0])
|
||||
assert submitted == (["18-1", "18-2", "18-3"] if deepen else ["18-1", "18-2"])
|
||||
assert scan.collection.remaining == {f"1:{episode}" for episode in range(18, 35)}
|
||||
assert not scan.submitted
|
||||
assert scan.ended
|
||||
if not deepen:
|
||||
assert "无法打开链接" in scan.progress_text()
|
||||
assert "2026-11-27 19:30:00" in scan.progress_text()
|
||||
|
||||
|
||||
def test_cooling_target_keeps_other_targets_and_new_alternatives_searchable(owner, monkeypatch):
|
||||
"""
|
||||
退避只暂停已有候选全冷却的目标;其他缺集驱动的新页发现可用版本时重新放行该目标。
|
||||
"""
|
||||
calls = pages(owner, monkeypatch, {0: [torrent(18)], 1: [torrent(17), torrent(18, 2)]})
|
||||
failure = DownloadFailureSnapshot("failure", "无法打开链接", "2026-11-27 19:30:00")
|
||||
|
||||
def cooldowns(items):
|
||||
"""
|
||||
仅第十八集旧版本命中退避。
|
||||
"""
|
||||
return {item.torrent_info.search_resource_id: failure for item in items
|
||||
if item.torrent_info.description == "18-1"}
|
||||
|
||||
scan = SearchScan(owner=owner, plan=plan([17, 18, 19]), candidate_cooldowns=cooldowns)
|
||||
|
||||
def submit(items, ready):
|
||||
"""
|
||||
旧版本不提交,新资源按实际覆盖目标结算。
|
||||
"""
|
||||
return ready if any(item.torrent_info.description != "18-1" for item in items) else set()
|
||||
|
||||
scan.run(submit)
|
||||
|
||||
assert calls == [0, 1]
|
||||
assert scan.collection.remaining == {"1:19"}
|
||||
assert scan.submitted == {"1:17", "1:18"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cleared", [False, True])
|
||||
def test_candidate_cooldown_survives_checkpoint_and_manual_clear_reopens_only_missing(owner, monkeypatch, cleared):
|
||||
"""
|
||||
检查点保留冷却与真实缺集;人工清除后重新受理该候选,未清除时不重复提交。
|
||||
"""
|
||||
pages(owner, monkeypatch, {0: [torrent(18)]})
|
||||
failure = DownloadFailureSnapshot("failure", "无法打开链接", "2026-11-27 19:30:00")
|
||||
|
||||
def cooldowns(items):
|
||||
"""
|
||||
初次仍处于冷却,恢复时按当前台账是否已清除返回事实。
|
||||
"""
|
||||
return {item.torrent_info.search_resource_id: failure for item in items}
|
||||
|
||||
search_plan = plan([18, 19])
|
||||
scan = SearchScan(owner=owner, plan=search_plan, candidate_cooldowns=cooldowns)
|
||||
for key in list(scan.collection.sources):
|
||||
scan.step(key)
|
||||
scan.choose({"1:18"}, lambda _items, _ready: set())
|
||||
state = scan.state()
|
||||
snapshot = SearchSessionSnapshot("cooldown", 1, encode_search_state(state))
|
||||
restored = SearchScan(owner=owner, plan=search_plan, snapshot=snapshot,
|
||||
candidate_cooldowns=(lambda _items: {}) if cleared else cooldowns)
|
||||
# 只恢复下载票据的边界被隔离;检查点、退避复核及目标结算仍使用真实实现。
|
||||
restored.live = scan.live
|
||||
submitted = []
|
||||
|
||||
def submit(items, ready):
|
||||
"""
|
||||
记录恢复后真正提交的候选,并结算已提交集数。
|
||||
"""
|
||||
submitted.extend(items)
|
||||
return ready
|
||||
|
||||
restored.run(submit)
|
||||
|
||||
assert len(submitted) == int(cleared)
|
||||
assert restored.collection.remaining == ({"1:19"} if cleared else {"1:18", "1:19"})
|
||||
assert ("无法打开链接" in restored.progress_text()) is not cleared
|
||||
|
||||
|
||||
def pages(owner, monkeypatch, data):
|
||||
"""
|
||||
用内存页面替换站点请求,并返回请求页码记录。
|
||||
"""
|
||||
calls = []
|
||||
def request(**params):
|
||||
"""
|
||||
返回本页内存数据并记录真实页面观察事实。
|
||||
"""
|
||||
page = params["page"]
|
||||
calls.append(page)
|
||||
values = data.get(page, [])
|
||||
|
||||
@@ -34,6 +34,9 @@ def repository(tmp_path):
|
||||
|
||||
|
||||
def _set_lease(engine, token):
|
||||
"""
|
||||
在隔离数据库中更换任务租约,模拟队列把任务交给新执行者。
|
||||
"""
|
||||
with sessionmaker(bind=engine)() as session:
|
||||
session.execute(update(SubscriptionSearchTask).values(lease_token=token))
|
||||
session.commit()
|
||||
@@ -112,6 +115,46 @@ def test_partial_submission_does_not_finish_an_interrupted_search_round(system_s
|
||||
queue.release_task.assert_called_once()
|
||||
|
||||
|
||||
def test_download_cooldown_completes_task_and_batch_with_retry_reason(repository):
|
||||
"""
|
||||
下载冷却正常结束搜索任务和批次,并通过执行状态返回原因与重试时间,不残留站点等待。
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.application.subscription.observability import finish_returned_search_task
|
||||
from app.application.subscription.status import SubscriptionExecutionStatusService
|
||||
from app.db.adapters.subscriptionsearch import TransactionalSubscriptionSearchRepository
|
||||
from app.db.adapters.subscriptionstatus import _task
|
||||
from app.db.models.subscriptionsearch import SubscriptionSearchBatch
|
||||
|
||||
_sessions, engine = repository
|
||||
factory = sessionmaker(bind=engine)
|
||||
queue = TransactionalSubscriptionSearchRepository(factory)
|
||||
with factory() as session:
|
||||
session.add(SubscriptionSearchBatch(batch_id="batch", source="manual", state="running", total_count=1,
|
||||
created_at="2026-11-26T00:00:00+00:00", updated_at="2026-11-26T00:00:00+00:00"))
|
||||
session.commit()
|
||||
reason = "E18 的候选资源暂时跳过(原因:无法打开链接),最早 2026-11-27 19:30:00 后可重试"
|
||||
execution = SimpleNamespace(download_started=False, incremental_search=True, scan_finished=True,
|
||||
result_message=reason, is_expired=lambda: False)
|
||||
|
||||
result = finish_returned_search_task(queue=queue, task_id="task", lease_token="old", subscription_id=1,
|
||||
execution_context=execution, system_stopped=False, cancel_requested=False)
|
||||
|
||||
assert result == (1, "completed", None)
|
||||
with factory() as session:
|
||||
task = _task(session.query(SubscriptionSearchTask).filter_by(task_id="task").one())
|
||||
batch = queue.get_batch("batch")
|
||||
status = SubscriptionExecutionStatusService._from_task(task)
|
||||
assert status.state == "completed"
|
||||
assert status.error == reason
|
||||
assert status.submitted_count == 0
|
||||
assert status.next_run_at is None
|
||||
assert batch.state == "completed"
|
||||
assert batch.finished_count == 1
|
||||
assert batch.last_error == reason
|
||||
|
||||
|
||||
def test_finished_round_removes_its_checkpoint_only_with_the_current_lease_and_version(repository):
|
||||
"""
|
||||
完成轮次时仅允许当前租约与版本删除检查点。
|
||||
|
||||
@@ -14,6 +14,7 @@ import app.chain.download.selection as download_selection
|
||||
import app.chain.subscribe.policy as subscribe_policy
|
||||
import app.chain.subscribe.refresh as subscribe_refresh
|
||||
import app.chain.subscribe.search as subscribe_search
|
||||
from app.application.download.failures import DownloadFailureSnapshot
|
||||
from app.application.site.observation import report_site_search_outcome, report_site_search_page
|
||||
from app.application.subscription.contract import SubscriptionSnapshot, build_subscribe_meta
|
||||
from app.application.subscription.priority import (
|
||||
@@ -83,6 +84,56 @@ def _missing(scope, item):
|
||||
subscribe=item, meta=build_subscribe_meta(item), mediainfo=scope.media, mediakey="tmdb:1")[1]
|
||||
|
||||
|
||||
def test_subscription_stops_deep_paging_when_available_episode_is_cooling(subscription, monkeypatch):
|
||||
"""
|
||||
真实订阅择源跳过连载最新集的冷却候选后直接收尾,不为重复候选翻满二十页,也不误结算缺集。
|
||||
"""
|
||||
scope = subscription
|
||||
current = replace(scope.initial, total_episode=34, manual_total_episode=34, note=list(range(1, 18)))
|
||||
scope.current["value"] = current
|
||||
scope.media.seasons = {1: list(range(1, 35))}
|
||||
target = SubscriptionSearchTarget(current, build_subscribe_meta(current), scope.media,
|
||||
_missing(scope, current), "tmdb:1")
|
||||
search = SearchChain()
|
||||
monkeypatch.setattr(search, "_sync_indexers", lambda _sites: [{"id": 1, "name": "A", "parser": "mTorrent"}])
|
||||
monkeypatch.setattr(search, "search_plugin_torrents", lambda **_params: [])
|
||||
monkeypatch.setattr(scope.chain, "get_sub_sites", lambda _subscribe: [1])
|
||||
monkeypatch.setattr(subscribe_search, "DownloadChain", lambda: scope.download)
|
||||
monkeypatch.setattr(subscribe_search, "_subscription_search_strategy", lambda _best: "smart")
|
||||
calls = []
|
||||
|
||||
def request(**params):
|
||||
"""
|
||||
每页保留同一十八集候选并改变无关条目,模拟搜索参数失效却有不同整页摘要的站点。
|
||||
"""
|
||||
calls.append(params["page"])
|
||||
items = [TorrentInfo(site=1, site_name="A", title="Example Show S01E18",
|
||||
enclosure="https://site.example/download?id=18", pri_order=100),
|
||||
TorrentInfo(site=1, site_name="A", title=f"Unrelated Movie {params['page']}",
|
||||
enclosure=f"https://site.example/download?id={100 + params['page']}")]
|
||||
report_site_search_outcome(attempted=True, outcome="success")
|
||||
report_site_search_page(raw_count=len(items), has_more=True)
|
||||
return items
|
||||
|
||||
def active_failures(contexts, **_params):
|
||||
"""
|
||||
使用真实资源指纹返回仍有效的取链接失败记录。
|
||||
"""
|
||||
return {fingerprint: DownloadFailureSnapshot(fingerprint, "无法打开链接", "2026-11-27 19:30:00")
|
||||
for context in contexts
|
||||
if (fingerprint := scope.download._build_download_failure_fingerprint(context))}
|
||||
|
||||
scope.download._active_download_failure_fingerprints.side_effect = active_failures
|
||||
monkeypatch.setattr(search, "search_site_torrents", request)
|
||||
|
||||
_process_paged_subscription(scope.chain, current, search, target, SystemConfigKey.SubscribeFilterRuleGroups, None)
|
||||
|
||||
assert calls == [0]
|
||||
scope.download.download_single.assert_not_called()
|
||||
scope.finished.assert_not_called()
|
||||
assert set(_missing(scope, scope.current["value"])["tmdb:1"][1].episodes) == set(range(18, 35))
|
||||
|
||||
|
||||
def test_cumulative_episode_subscription_reaches_download_submission(subscription, monkeypatch):
|
||||
"""
|
||||
人工累计范围经真实缺集计算、分页识别和下载选集后提交 1180 集,且不提前完成订阅。
|
||||
|
||||
@@ -5,9 +5,13 @@
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.subscription.candidates import CandidateIndex
|
||||
from app.application.subscription.contract import SubscriptionSnapshot
|
||||
from app.application.subscription.facts import FreshFactLease
|
||||
from app.chain.subscribe import match as subscribe_match
|
||||
from app.chain.subscribe.facade import SubscribeChain
|
||||
from app.chain.torrents import TorrentsChain
|
||||
from app.domain.context import Context, MediaInfo, TorrentInfo
|
||||
from app.domain.metainfo import MetaInfo
|
||||
@@ -81,6 +85,32 @@ def _candidate_count(groups: dict[str, list[Context]]) -> int:
|
||||
return sum(len(contexts) for contexts in groups.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("custom_words", [None, "旧名 => 新名"])
|
||||
def test_match_prunes_clear_type_and_season_conflicts_before_external_recognition(monkeypatch, custom_words):
|
||||
"""
|
||||
RSS 重识别前排除明确类型或季号冲突,自定义识别词、未知类型和年份差异继续保守处理。
|
||||
"""
|
||||
subscribe = _subscribe(custom_words=custom_words)
|
||||
related = _context("Alias 1999 S01E18", media_type=MediaType.TV)
|
||||
movie = _context("Unrelated Movie 2026", media_type=MediaType.MOVIE, season=None)
|
||||
other_season = _context("Another Show S02E01", media_type=MediaType.TV, season=2)
|
||||
unknown = _context("Unknown Work", media_type=MediaType.UNKNOWN, season=None)
|
||||
contexts = [related, movie, other_season, unknown]
|
||||
recognize = Mock(return_value=None)
|
||||
chain = SubscribeChain()
|
||||
monkeypatch.setattr(chain, "subscription_repository", Mock(list=Mock(return_value=[subscribe])))
|
||||
monkeypatch.setattr(chain, "_check_match_subscription", Mock())
|
||||
monkeypatch.setattr(subscribe_match, "MediaChain", lambda: SimpleNamespace(recognize_by_meta=recognize))
|
||||
|
||||
chain.match({"example.com": contexts})
|
||||
|
||||
assert recognize.call_count == (4 if custom_words else 2)
|
||||
assert related.media_recognize_fail_count == 1
|
||||
assert unknown.media_recognize_fail_count == 1
|
||||
assert movie.media_recognize_fail_count == int(bool(custom_words))
|
||||
assert other_season.media_recognize_fail_count == int(bool(custom_words))
|
||||
|
||||
|
||||
def test_refresh_returns_complete_cache_with_new_candidates():
|
||||
"""
|
||||
刷新结果必须包含既有缓存和本轮新增资源的完整候选。
|
||||
|
||||
@@ -2,16 +2,21 @@
|
||||
种子 GET 的有界重试、缓存与冷却策略离线回归。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
from requests import Response
|
||||
from requests.exceptions import ConnectionError as RequestsConnectionError
|
||||
from requests.exceptions import ProxyError, RequestException, SSLError, Timeout
|
||||
|
||||
import app.api.endpoints.torrent as torrent_api
|
||||
import app.application.torrent.download as download
|
||||
import app.chain.download.failure as failure_owner
|
||||
import app.chain.download.submission as submission
|
||||
@@ -25,11 +30,11 @@ from app.chain.download.failure import (
|
||||
)
|
||||
from app.db.adapters.download import TransactionalDownloadFailureRepository
|
||||
from app.db.models.downloadfailure import DownloadFailure
|
||||
from app.db.session import SessionFactory
|
||||
from app.db.session import SessionFactory, async_session_scope
|
||||
from app.domain.context import Context, MediaInfo, TorrentInfo
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.schemas.media import build_media_key, resolve_media_identity
|
||||
from app.schemas.types import MediaType
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
URL = "https://tracker.example/download.php?id=39"
|
||||
CONTENT = b"d4:infod4:name10:Series.mkv6:lengthi1eee"
|
||||
@@ -58,7 +63,11 @@ def boundary(monkeypatch):
|
||||
monkeypatch.setattr(download, "FileCache", Mock(return_value=cache))
|
||||
sleep = Mock()
|
||||
monkeypatch.setattr(download.time, "sleep", sleep)
|
||||
monkeypatch.setattr(download, "TTLCache", Mock(return_value={}))
|
||||
invalid = {}
|
||||
monkeypatch.setattr(download, "TTLCache", Mock(return_value=invalid))
|
||||
monkeypatch.setattr(download, "AsyncTTLCache", Mock(return_value=SimpleNamespace(
|
||||
pop=AsyncMock(side_effect=lambda key, default: invalid.pop(key, default)),
|
||||
)))
|
||||
helper = download.TorrentHelper()
|
||||
helper.add_invalid = Mock(wraps=helper.add_invalid)
|
||||
return helper, port, cache, sleep
|
||||
@@ -103,6 +112,61 @@ def test_exhausted_retry_is_bounded_and_does_not_poison_url(boundary, status):
|
||||
cache.set.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error,reason", [(ProxyError, "代理连接失败"), (Timeout, "请求超时"),
|
||||
(SSLError, "TLS 连接失败"),
|
||||
(RequestsConnectionError, "网络连接失败"), (RequestException, "网络请求失败")])
|
||||
@pytest.mark.parametrize("cache_invalid,attempts", [(True, 3), (False, 1)])
|
||||
def test_torrent_network_failures_preserve_safe_diagnostics(boundary, monkeypatch, error, reason,
|
||||
cache_invalid, attempts):
|
||||
"""
|
||||
真实传输适配器把最终网络故障类别传到下载层,保留重试预算且不把地址或代理凭据暴露给用户。
|
||||
"""
|
||||
from app.startup.composition import site as site_composition
|
||||
|
||||
helper, _, cache, sleep = boundary
|
||||
transport = Mock()
|
||||
transport.get_res.side_effect = error("https://user:password@site.example/download?passkey=private-key")
|
||||
monkeypatch.setattr(site_composition, "RequestUtils", Mock(return_value=transport))
|
||||
monkeypatch.setattr(download, "_require_torrent_port", lambda: site_composition._TorrentHttpAdapter())
|
||||
|
||||
result = helper.download_torrent(URL, cache_invalid=cache_invalid)
|
||||
|
||||
assert reason in result[4]
|
||||
assert "passkey" not in result[4]
|
||||
assert "password" not in result[4]
|
||||
assert "private-key" not in result[4]
|
||||
assert transport.get_res.call_count == attempts
|
||||
assert transport.get_res.call_args.kwargs["raise_exception"] is True
|
||||
assert sleep.call_count == attempts - 1
|
||||
helper.add_invalid.assert_not_called()
|
||||
cache.set.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [ProxyError, Timeout])
|
||||
def test_confirmation_post_keeps_network_diagnostic_without_replaying_side_effect(boundary, monkeypatch, error):
|
||||
"""
|
||||
首次下载确认 POST 遇到代理或超时异常只提交一次,并把安全诊断交还调用方。
|
||||
"""
|
||||
from app.startup.composition import site as site_composition
|
||||
|
||||
helper, _, _, sleep = boundary
|
||||
transport = Mock()
|
||||
transport.get_res.return_value = _response(content=(
|
||||
'下载种子文件<form action="?"><input name="confirm" value="yes"></form>'.encode()
|
||||
))
|
||||
transport.post_res.side_effect = error("fictional connection failure")
|
||||
monkeypatch.setattr(site_composition, "RequestUtils", Mock(return_value=transport))
|
||||
monkeypatch.setattr(download, "_require_torrent_port", lambda: site_composition._TorrentHttpAdapter())
|
||||
|
||||
result = helper.download_torrent(URL)
|
||||
|
||||
assert "代理连接失败" in result[4] if error is ProxyError else "请求超时" in result[4]
|
||||
transport.get_res.assert_called_once()
|
||||
transport.post_res.assert_called_once()
|
||||
sleep.assert_not_called()
|
||||
helper.add_invalid.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [401, 404, 410, 429])
|
||||
def test_permanent_errors_and_rate_limit_are_not_retried(boundary, status):
|
||||
"""
|
||||
@@ -586,6 +650,143 @@ def _duplicate_backoff_context():
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manual_reidentify(boundary, db, monkeypatch):
|
||||
"""
|
||||
保留真实下载失败仓储、无效地址缓存和重新识别接口,仅隔离媒体与种子快照端口。
|
||||
"""
|
||||
db.watermark(DownloadFailure)
|
||||
helper = boundary[0]
|
||||
chain = object.__new__(DownloadChain)
|
||||
chain.download_failure_repository = TransactionalDownloadFailureRepository(SessionFactory, async_session_scope)
|
||||
target = _duplicate_backoff_context()
|
||||
target.media_info = MediaInfo(type=MediaType.TV, title="Series", media_source=MediaSource.TMDB, media_id="1")
|
||||
target.candidate_recognized = False
|
||||
target.media_info_is_target = True
|
||||
target.media_recognize_fail_count = 3
|
||||
original = chain._record_download_failure(target, "无法打开链接", source="Subscribe|1")
|
||||
duplicate = chain._record_duplicate_download_backoff(target, source="Subscribe|1")
|
||||
other = copy.deepcopy(target)
|
||||
other.torrent_info.enclosure = URL.replace("39", "40")
|
||||
unrelated = chain._record_download_failure(other, "无法打开链接", source="Subscribe|1")
|
||||
helper.add_invalid(target.torrent_info.enclosure)
|
||||
helper.add_invalid(other.torrent_info.enclosure)
|
||||
cache_chain = Mock()
|
||||
cache_chain.async_get_torrents = AsyncMock(return_value={"tracker.example": [target]})
|
||||
cache_chain.split_cache_contexts.return_value = ({"tracker.example": [target]}, {})
|
||||
cache_chain.cache_files.return_value = ("video", "music")
|
||||
cache_chain.async_save_cache = AsyncMock()
|
||||
media_chain = SimpleNamespace(async_recognize_media=AsyncMock(return_value=copy.deepcopy(target.media_info)))
|
||||
monkeypatch.setattr(torrent_api, "TorrentsChain", lambda: cache_chain)
|
||||
monkeypatch.setattr(torrent_api, "MediaChain", lambda: media_chain)
|
||||
monkeypatch.setattr(torrent_api, "DownloadChain", lambda: chain)
|
||||
return SimpleNamespace(chain=chain, target=target, other=other, cache=cache_chain, media=media_chain,
|
||||
helper=helper, original=original, duplicate=duplicate, unrelated=unrelated)
|
||||
|
||||
|
||||
def _reidentify_retry_target(scope, media_id="1"):
|
||||
"""
|
||||
通过现有管理员重识别入口处理目标缓存,不主动调用下载器。
|
||||
"""
|
||||
torrent = scope.target.torrent_info
|
||||
return asyncio.run(torrent_api.reidentify_cache(
|
||||
domain="tracker.example", torrent_hash=torrent_api.HashUtils.md5(f"{torrent.title}{torrent.description}"),
|
||||
media_source=MediaSource.TMDB, media_id=media_id, _=Mock(),
|
||||
))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("identity_changed", [False, True])
|
||||
def test_manual_reidentify_releases_only_that_resources_failure(manual_reidentify, identity_changed):
|
||||
"""
|
||||
手工重识别同一身份或修正身份后,清除前后失败指纹和原地址标记,保留其他资源及重复提交保护。
|
||||
"""
|
||||
scope = manual_reidentify
|
||||
failures = [scope.original]
|
||||
if identity_changed:
|
||||
corrected = copy.deepcopy(scope.target)
|
||||
corrected.media_info.media_id = "2"
|
||||
failures.append(scope.chain._record_download_failure(corrected, "无法打开链接", source="Subscribe|1"))
|
||||
scope.media.async_recognize_media.return_value = corrected.media_info
|
||||
|
||||
response = _reidentify_retry_target(scope, media_id="2" if identity_changed else "1")
|
||||
|
||||
assert response.success
|
||||
active = scope.chain.download_failure_repository.get_active_by_fingerprints(
|
||||
failures + [scope.unrelated, scope.duplicate], "0000",
|
||||
)
|
||||
assert set(active) == {scope.unrelated, scope.duplicate}
|
||||
assert not scope.helper.is_invalid(scope.target.torrent_info.enclosure)
|
||||
assert scope.helper.is_invalid(scope.other.torrent_info.enclosure)
|
||||
assert scope.target.candidate_recognized
|
||||
assert not scope.target.media_info_is_target
|
||||
assert scope.target.media_recognize_fail_count == 0
|
||||
assert scope.target.match_source == str(MediaSource.TMDB)
|
||||
scope.cache.async_save_cache.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["recognition", "save", "reset", "reset_commit"])
|
||||
def test_manual_reidentify_does_not_clear_backoff_before_success(manual_reidentify, monkeypatch, failure):
|
||||
"""
|
||||
识别无结果、缓存保存失败或清理事务失败时,不错误放行资源,也不把未完成的清理返回为成功。
|
||||
"""
|
||||
scope = manual_reidentify
|
||||
if failure == "recognition":
|
||||
scope.media.async_recognize_media.return_value = None
|
||||
elif failure == "save":
|
||||
scope.cache.async_save_cache.side_effect = OSError("fictional cache write failure")
|
||||
elif failure == "reset":
|
||||
monkeypatch.setattr(scope.chain.download_failure_repository, "async_delete_by_fingerprints",
|
||||
AsyncMock(side_effect=OSError("fictional database failure")))
|
||||
else:
|
||||
from app.db.adapters.download import SqlAlchemyAsyncUnitOfWork
|
||||
|
||||
monkeypatch.setattr(SqlAlchemyAsyncUnitOfWork, "commit", AsyncMock(side_effect=OSError("fictional commit failure")))
|
||||
|
||||
response = _reidentify_retry_target(scope)
|
||||
|
||||
assert response.success is (failure == "recognition")
|
||||
active = scope.chain.download_failure_repository.get_active_by_fingerprints([scope.original], "0000")
|
||||
assert scope.original in active
|
||||
assert scope.helper.is_invalid(scope.target.torrent_info.enclosure)
|
||||
if failure.startswith("reset"):
|
||||
assert "清除下载失败记录失败" in response.message
|
||||
|
||||
|
||||
def test_empty_failure_clear_does_not_delete_other_resources(manual_reidentify):
|
||||
"""
|
||||
没有明确资源指纹的清理请求幂等返回,不退化为全表或按媒体删除。
|
||||
"""
|
||||
scope = manual_reidentify
|
||||
assert asyncio.run(scope.chain.download_failure_repository.async_delete_by_fingerprints([])) == 0
|
||||
assert scope.chain.download_failure_repository.get_active_by_fingerprints([scope.original], "0000")
|
||||
|
||||
|
||||
def test_manual_retry_requires_an_async_database_boundary():
|
||||
"""
|
||||
未装配异步会话时拒绝清理,不在请求事件循环中退回同步事务。
|
||||
"""
|
||||
repository = TransactionalDownloadFailureRepository(SessionFactory)
|
||||
with pytest.raises(RuntimeError, match="异步会话尚未装配"):
|
||||
asyncio.run(repository.async_delete_by_fingerprints(["missing"]))
|
||||
|
||||
|
||||
def test_invalid_marker_clear_uses_the_same_sync_and_async_cache_region():
|
||||
"""
|
||||
真实缓存代理中,同步下载写入的无效地址能由人工重试的异步路径清除。
|
||||
"""
|
||||
helper = download.TorrentHelper()
|
||||
url = "https://tracker.example/download.php?id=manual-retry-cache-parity"
|
||||
try:
|
||||
helper.add_invalid(url)
|
||||
assert helper.is_invalid(url)
|
||||
asyncio.run(helper.async_remove_invalid(url))
|
||||
assert not helper.is_invalid(url)
|
||||
asyncio.run(helper.async_remove_invalid(url))
|
||||
assert not helper.is_invalid(url)
|
||||
finally:
|
||||
helper._invalid_torrents.pop(url, False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source,recorded", [("Subscribe|1", True), ("MoviePilot|手动下载", False)])
|
||||
def test_duplicate_submission_backoff_is_subscribe_only_and_long(source, recorded):
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user