mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 16:36:28 +08:00
perf(subscription): optimize automatic refresh scheduling
This commit is contained in:
218
app/application/subscription/refresh.py
Normal file
218
app/application/subscription/refresh.py
Normal file
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
自动订阅刷新按站点分配每日时间片,并合并错过的触发和失败冷却。
|
||||
|
||||
只保存可重建的排程事实,不作为执行队列;在途工作由调用方持有至真实结束。
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
import secrets
|
||||
from bisect import bisect_right
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Any, Optional, cast
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RefreshPolicy:
|
||||
"""
|
||||
单站每天的刷新预算和时间分布。
|
||||
|
||||
:param timezone_name: 排程使用的本地时区
|
||||
:param daily_count: 每个排程日分配的时间片数,包含夜间次数
|
||||
:param night_count: 23 点至次日 7 点的次数;其余次数分配到白天
|
||||
:param concurrency: 不同站点同时处理的上限,同站始终串行
|
||||
:param match_interval: 两次共享候选匹配之间的最小间隔,单位秒
|
||||
"""
|
||||
|
||||
timezone_name: str = "Asia/Shanghai"
|
||||
daily_count: int = 36
|
||||
night_count: int = 4
|
||||
concurrency: int = 2
|
||||
match_interval: int = 300
|
||||
|
||||
def slots(self, anchor: datetime, seed: str, site_id: int) -> list[datetime]:
|
||||
"""
|
||||
在每个时间片中间的 40% 范围抖动,使相邻间隔有上界且每日重新分散。
|
||||
|
||||
:param anchor: 排程日的日期,排程日从当地 7 点开始
|
||||
:param seed: 当前实例持久保存的随机盐,避免不同实例请求同步
|
||||
:param site_id: 站点稳定标识,不使用域名或认证信息
|
||||
:return: 按时间升序排列的当天全部计划时间
|
||||
"""
|
||||
start = anchor.replace(hour=7, minute=0, second=0, microsecond=0)
|
||||
result = []
|
||||
for phase, count, hours in (("day", self.daily_count - self.night_count, 16),
|
||||
("night", self.night_count, 8)):
|
||||
if count:
|
||||
# 使用时间戳划分时间片,夏令时切换时仍返回明确的真实时间。
|
||||
end = start + timedelta(hours=hours)
|
||||
width = (end.timestamp() - start.timestamp()) / count
|
||||
for index in range(count):
|
||||
identity = f"{seed}:{site_id}:{anchor.date()}:{phase}:{index}"
|
||||
fraction = int.from_bytes(hashlib.sha256(identity.encode()).digest()[:8]) / 2**64
|
||||
offset = (index + 0.3 + fraction * 0.4) * width
|
||||
result.append(datetime.fromtimestamp(start.timestamp() + offset, start.tzinfo))
|
||||
start += timedelta(hours=hours)
|
||||
return result
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RefreshSiteState:
|
||||
"""
|
||||
一个站点的排程和健康事实,不包含凭据或资源内容。
|
||||
|
||||
:param slot: 最近已实际访问的时间片,以 UTC 时间戳标识
|
||||
:param next_due: 最早再次检查的 UTC 时间戳
|
||||
:param failures: 连续失败次数;成功空列表也会清零
|
||||
:param last_attempt: 最近实际访问开始时间;0 表示尚未访问
|
||||
:param last_success: 最近成功完成时间;0 表示尚未成功
|
||||
"""
|
||||
|
||||
slot: float = 0
|
||||
next_due: float = 0
|
||||
failures: int = 0
|
||||
last_attempt: float = 0
|
||||
last_success: float = 0
|
||||
|
||||
|
||||
class RefreshSchedule:
|
||||
"""
|
||||
在有界时间片预算内选择到期站点,重启和热重载继续使用已保存的进度。
|
||||
"""
|
||||
|
||||
def __init__(self, policy: RefreshPolicy, snapshot: Any = None) -> None:
|
||||
"""
|
||||
读取内部缓存;旧版或损坏快照重建排程,不影响资源缓存。
|
||||
|
||||
:param policy: 当前自动刷新策略
|
||||
:param snapshot: 上次保存的内部排程快照,无快照时生成实例随机盐
|
||||
"""
|
||||
self.policy = policy
|
||||
self.timezone = ZoneInfo(policy.timezone_name)
|
||||
data = snapshot if isinstance(snapshot, dict) and snapshot.get("version") == 1 else {}
|
||||
seed = data.get("seed")
|
||||
self.seed = seed if isinstance(seed, str) else secrets.token_hex(16)
|
||||
self.needs_match = data.get("needs_match") is True
|
||||
try:
|
||||
match_after = float(data.get("match_after") or 0)
|
||||
self.match_after = match_after if math.isfinite(match_after) and match_after >= 0 else 0
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
self.match_after = 0
|
||||
self.states: dict[int, RefreshSiteState] = {}
|
||||
self._windows: dict[int, tuple[date, list[float]]] = {}
|
||||
sites = data.get("sites")
|
||||
for site_id, raw in (sites if isinstance(sites, dict) else {}).items():
|
||||
try:
|
||||
state = RefreshSiteState(**raw)
|
||||
if not all(math.isfinite(value) and value >= 0 for value in asdict(state).values()):
|
||||
continue
|
||||
self.states[int(site_id)] = state
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
continue
|
||||
|
||||
def snapshot(self) -> dict[str, Any]:
|
||||
"""
|
||||
返回可持久化的内部快照,不保存线程或在途所有权。
|
||||
"""
|
||||
return {"version": 1, "seed": self.seed, "needs_match": self.needs_match, "match_after": self.match_after,
|
||||
"sites": {str(site_id): asdict(state) for site_id, state in self.states.items()}}
|
||||
|
||||
def matching_due(self, now: datetime) -> bool:
|
||||
"""
|
||||
只有待匹配且合并窗口结束时才检查全部订阅,避免站点数放大全量匹配次数。
|
||||
"""
|
||||
return self.needs_match and now.timestamp() >= self.match_after
|
||||
|
||||
def matched(self, now: datetime) -> None:
|
||||
"""
|
||||
匹配成功后清除意图并开启合并窗口;失败时调用方保留意图与原到期时间。
|
||||
"""
|
||||
self.needs_match = False
|
||||
self.match_after = now.timestamp() + self.policy.match_interval
|
||||
|
||||
def window(self, site_id: int, now: datetime) -> tuple[float, float]:
|
||||
"""
|
||||
返回最近已到期与下一时间片;多日停机只保留最近一次机会。
|
||||
|
||||
:param site_id: 当前站点的稳定标识
|
||||
:param now: 需要定位的真实时间,按策略时区确定排程日
|
||||
:return: 最近已到期及下一时间片的 UTC 时间戳
|
||||
"""
|
||||
local = now.astimezone(self.timezone)
|
||||
cached = self._windows.get(site_id)
|
||||
if cached is None or cached[0] != local.date():
|
||||
slots = sorted(slot.timestamp() for days in (-1, 0, 1)
|
||||
for slot in self.policy.slots(local + timedelta(days=days), self.seed, site_id))
|
||||
self._windows[site_id] = local.date(), slots
|
||||
else:
|
||||
slots = cached[1]
|
||||
index = bisect_right(slots, now.timestamp())
|
||||
return slots[index - 1], slots[index]
|
||||
|
||||
def due(self, site_ids: list[int], now: datetime) -> list[int]:
|
||||
"""
|
||||
按等待时间选择到期站点,新站在五分钟内分散首次检查。
|
||||
|
||||
:param site_ids: 当前有效和仍在途站点,其余排程状态回收
|
||||
:param now: 当前真实时间,调用方在每轮扫描读取
|
||||
:return: 按到期时间和站点 ID 稳定排序的站点清单
|
||||
"""
|
||||
selected = set(site_ids)
|
||||
self.states = {site_id: state for site_id, state in self.states.items() if site_id in selected}
|
||||
self._windows = {site_id: window for site_id, window in self._windows.items() if site_id in selected}
|
||||
timestamp = now.timestamp()
|
||||
due = []
|
||||
for site_id in site_ids:
|
||||
state = self.states.get(site_id)
|
||||
if state is None:
|
||||
offset = int(hashlib.sha256(f"{self.seed}:{site_id}:initial".encode()).hexdigest()[:8], 16) % 300
|
||||
state = self.states[site_id] = RefreshSiteState(next_due=timestamp + offset)
|
||||
previous, following = self.window(site_id, now)
|
||||
if state.slot >= previous:
|
||||
state.next_due = max(state.next_due, following)
|
||||
elif state.next_due <= timestamp:
|
||||
due.append(site_id)
|
||||
return sorted(due, key=lambda site_id: (self.states[site_id].next_due, site_id))
|
||||
|
||||
def finish(self, site_id: int, started: datetime, fact: dict[str, object], now: datetime) -> None:
|
||||
"""
|
||||
只有真实访问消耗时间片;限流延后保留一次机会,失败按站点退避。
|
||||
|
||||
:param site_id: 本次工作所属站点
|
||||
:param started: 实际工作提交时间,计算本次消费的时间片
|
||||
:param fact: 抓取结果,包含 attempted、status 及可选 retry_after 秒数
|
||||
:param now: 工作真实完成时间
|
||||
"""
|
||||
state = self.states[site_id]
|
||||
previous, following = self.window(site_id, started)
|
||||
attempted = fact.get("attempted", True)
|
||||
status = fact.get("status", "failed")
|
||||
if attempted:
|
||||
state.slot = previous
|
||||
state.last_attempt = started.timestamp()
|
||||
self.needs_match = True
|
||||
if status == "success":
|
||||
state.failures = 0
|
||||
state.last_success = now.timestamp()
|
||||
elif attempted:
|
||||
state.failures += 1
|
||||
if status == "deferred" or not attempted:
|
||||
state.next_due = now.timestamp() + float(cast(float, fact.get("retry_after") or 60))
|
||||
if attempted:
|
||||
state.next_due = max(state.next_due, started.timestamp() + 1200)
|
||||
else:
|
||||
# 不追加预算外重试;失败冷却可以跳过若干时间片,恢复时不补排历史请求。
|
||||
cooldown = min(7200, 300 * 2 ** min(state.failures, 5)) if state.failures else 0
|
||||
remote_cooldown = float(cast(float, fact.get("retry_after") or 0))
|
||||
state.next_due = max(following, started.timestamp() + 1200,
|
||||
now.timestamp() + max(cooldown, remote_cooldown))
|
||||
|
||||
def next_due(self) -> Optional[str]:
|
||||
"""
|
||||
返回最早计划检查时间,供日志和进度显示。
|
||||
"""
|
||||
if not self.states:
|
||||
return None
|
||||
return datetime.fromtimestamp(min(state.next_due for state in self.states.values()), timezone.utc).isoformat()
|
||||
@@ -163,14 +163,20 @@ class ChainBase(RecognitionMixin, MessageProcessingMixin, NotificationMixin, met
|
||||
raise
|
||||
return
|
||||
|
||||
def save_cache(self, cache: Any, filename: str) -> None:
|
||||
def save_cache(self, cache: Any, filename: str, *, strict: bool = False) -> None:
|
||||
"""
|
||||
保存缓存
|
||||
保存同步缓存,默认保留旧调用的失败日志合同。
|
||||
|
||||
:param cache: 待序列化的业务快照
|
||||
:param filename: 目标缓存键
|
||||
:param strict: 为 True 时向需要确认保存的用例传播失败
|
||||
"""
|
||||
try:
|
||||
self.filecache.set(filename, pickle.dumps(cache))
|
||||
except Exception as err:
|
||||
logger.error(f"保存缓存 {filename} 出错:{str(err)}")
|
||||
if strict:
|
||||
raise
|
||||
return
|
||||
|
||||
def remove_cache(self, filename: str) -> None:
|
||||
|
||||
@@ -119,6 +119,8 @@ if TYPE_CHECKING:
|
||||
get_subscribe_source_keyword: Callable[..., Any]
|
||||
get_subscribed_sites: Callable[..., Any]
|
||||
has_music_subscribe: Callable[..., Any]
|
||||
load_cache: Callable[..., Any]
|
||||
save_cache: Callable[..., Any]
|
||||
match: Callable[..., Any]
|
||||
media_exists: Callable[..., Any]
|
||||
media_files: Callable[..., Any]
|
||||
|
||||
162
app/chain/subscribe/poll.py
Normal file
162
app/chain/subscribe/poll.py
Normal file
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
自动订阅刷新以有限并发消费到期站点,健康站点先进入共享候选匹配。
|
||||
"""
|
||||
|
||||
from concurrent.futures import FIRST_COMPLETED, Future, wait
|
||||
from datetime import datetime, timezone
|
||||
from threading import Event
|
||||
from typing import Any, Callable, Optional, cast
|
||||
|
||||
from app.application.site.protocol import site_domain
|
||||
from app.application.subscription.refresh import RefreshPolicy, RefreshSchedule
|
||||
from app.chain.subscribe.contract import _SubscribeOwnerBase
|
||||
from app.chain.torrents import TorrentsChain
|
||||
from app.domain.context import Context
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.observability import record_metric
|
||||
from app.runtime.stop import runtime_stop_state
|
||||
from app.runtime.thread import ThreadHelper
|
||||
|
||||
# 缓存仅包含时间片和站点计数;不保存下载意图,不替代持久搜索队列。
|
||||
_SCHEDULE_CACHE = "__subscribe_refresh_schedule__"
|
||||
_POLL_SECONDS = 30
|
||||
# 合并窗口只保存安全结果计数,不落盘站点名称、资源、下载地址或错误原文。
|
||||
_FACT_FIELDS = frozenset({"id", "status", "attempted", "candidates", "new_candidates", "seconds", "retry_after"})
|
||||
RefreshResult = tuple[str, list[Context], dict[str, object]]
|
||||
|
||||
|
||||
class SubscriptionRefreshPoll:
|
||||
"""
|
||||
一轮自动刷新工作及其真实 Future 的单一 owner,不建立独立线程池。
|
||||
"""
|
||||
|
||||
def __init__(self, owner: _SubscribeOwnerBase, policy: RefreshPolicy,
|
||||
progress: Optional[Callable[..., None]] = None,
|
||||
stop_event: Optional[Event] = None) -> None:
|
||||
"""
|
||||
绑定订阅链、当前策略和进度;在运行入口读取最新配置与订阅范围。
|
||||
|
||||
:param owner: 提供订阅范围、匹配入口和内部缓存的订阅链
|
||||
:param policy: 本轮站点时间片与最大并发策略
|
||||
:param progress: 调度任务的可选同步进度回调
|
||||
:param stop_event: 协程宿主取消后的封口信号;不取消已经运行的同步 Future
|
||||
"""
|
||||
self.owner = owner
|
||||
self.progress = progress
|
||||
self.stop_event = stop_event
|
||||
self.torrents = TorrentsChain()
|
||||
snapshot = owner.load_cache(_SCHEDULE_CACHE)
|
||||
self.schedule = RefreshSchedule(policy, snapshot)
|
||||
self._saved_snapshot = snapshot
|
||||
self.pending: dict[Future[RefreshResult], tuple[int, datetime]] = {}
|
||||
raw_facts = snapshot.get("pending_facts", []) if isinstance(snapshot, dict) else []
|
||||
self.facts: dict[int, dict[str, object]] = {
|
||||
fact["id"]: {key: value for key, value in fact.items() if key in _FACT_FIELDS}
|
||||
for fact in raw_facts if isinstance(fact, dict) and isinstance(fact.get("id"), int)
|
||||
and fact["id"] in self.schedule.states
|
||||
} if isinstance(raw_facts, list) else {}
|
||||
self.finished = 0
|
||||
|
||||
@property
|
||||
def stopped(self) -> bool:
|
||||
"""
|
||||
系统关闭或本轮取消均停止新提交和匹配,已接受 Future 仍由 finally 收尾。
|
||||
"""
|
||||
return runtime_stop_state.is_system_stopped or bool(self.stop_event and self.stop_event.is_set())
|
||||
|
||||
def run(self) -> None:
|
||||
"""
|
||||
仅提交到期站点,在途时继续检查到期时间;关闭和异常均等待真实工作结束。
|
||||
"""
|
||||
try:
|
||||
while True:
|
||||
sites = self.owner.get_subscribed_sites()
|
||||
if sites is None or self.stopped:
|
||||
break
|
||||
indexers = self.torrents.refresh_indexers(sites)
|
||||
self._dispatch(indexers)
|
||||
if self.schedule.matching_due(datetime.now(timezone.utc)) and not self.stopped:
|
||||
self._match(indexers)
|
||||
if not self.pending:
|
||||
break
|
||||
completed, _ = wait(self.pending, timeout=_POLL_SECONDS, return_when=FIRST_COMPLETED)
|
||||
self._collect(completed)
|
||||
self._report()
|
||||
finally:
|
||||
# 同步工作不能被 Future.cancel 杀死;收尾前保留 Scheduler 的本轮所有权。
|
||||
if self.pending:
|
||||
wait(self.pending)
|
||||
self._collect(set(self.pending))
|
||||
self._save()
|
||||
|
||||
def _match(self, indexers: list[dict[str, Any]]) -> None:
|
||||
"""
|
||||
复用全部有效站点的共享候选排序;匹配异常时保留意图供下一轮恢复。
|
||||
"""
|
||||
domains = {site_domain(indexer.get("domain")) for indexer in indexers}
|
||||
candidates = {domain: contexts for domain, contexts in self.torrents.get_torrents().items()
|
||||
if domain in domains}
|
||||
names = {indexer["id"]: indexer.get("name") for indexer in indexers}
|
||||
facts = tuple({**fact, "name": names[site_id]} for site_id, fact in self.facts.items() if site_id in names)
|
||||
self.owner.match(candidates, mtype=None, site_facts=facts, source="automatic")
|
||||
self.schedule.matched(datetime.now(timezone.utc))
|
||||
self.facts.clear()
|
||||
self._save()
|
||||
|
||||
def _dispatch(self, indexers: list[dict[str, Any]]) -> None:
|
||||
"""
|
||||
按等待时间提交到期站点,已在途的站点只保留一次到期机会。
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
active_ids = {site_id for site_id, _ in self.pending.values()}
|
||||
by_id = {int(indexer["id"]): indexer for indexer in indexers}
|
||||
due = self.schedule.due(list(by_id.keys() | active_ids), now)
|
||||
for site_id in due:
|
||||
if len(self.pending) >= self.schedule.policy.concurrency or self.stopped:
|
||||
break
|
||||
if site_id in active_ids or site_id not in by_id:
|
||||
continue
|
||||
future = ThreadHelper().submit(self.torrents.refresh_site, by_id[site_id], "spider",
|
||||
self.owner.has_music_subscribe())
|
||||
self.pending[future] = site_id, now
|
||||
self._save()
|
||||
|
||||
def _collect(self, completed: set[Future[RefreshResult]]) -> None:
|
||||
"""
|
||||
单站失败只延后该站,其他已接受工作继续处理并保存独立进度。
|
||||
"""
|
||||
for future in completed:
|
||||
site_id, started = self.pending.pop(future)
|
||||
try:
|
||||
_, _, fact = future.result()
|
||||
except Exception as error:
|
||||
logger.error(f"站点 {site_id} 自动刷新失败:{type(error).__name__},请检查站点请求日志")
|
||||
fact = {"id": site_id, "status": "failed", "attempted": True}
|
||||
self.schedule.finish(site_id, started, fact, datetime.now(timezone.utc))
|
||||
self.facts[site_id] = {key: value for key, value in fact.items() if key in _FACT_FIELDS}
|
||||
self.finished += 1
|
||||
record_metric("subscription.refresh.site", owner="subscription", outcome=str(fact.get("status")))
|
||||
record_metric("subscription.refresh.site.duration", float(cast(float, fact.get("seconds") or 0)), owner="subscription")
|
||||
self._save()
|
||||
self._report()
|
||||
|
||||
def _save(self) -> None:
|
||||
"""
|
||||
保存可重建排程事实;失败向上传播,不能在未保存时宣称本轮完成。
|
||||
"""
|
||||
snapshot = self.schedule.snapshot()
|
||||
if self.facts:
|
||||
snapshot["pending_facts"] = list(self.facts.values())
|
||||
if snapshot != self._saved_snapshot:
|
||||
self.owner.save_cache(snapshot, _SCHEDULE_CACHE, strict=True)
|
||||
self._saved_snapshot = snapshot
|
||||
|
||||
def _report(self) -> None:
|
||||
"""
|
||||
汇报真实站点处理结果和下一次到期时间,空扫描不伪造站点刷新。
|
||||
"""
|
||||
if self.progress:
|
||||
self.progress(value=100 if not self.pending else 50,
|
||||
text=f"已刷新 {self.finished} 个站点" if self.finished else "暂无到期站点",
|
||||
data={"finished": self.finished, "running_sites": len(self.pending),
|
||||
"next_refresh_at": self.schedule.next_due()})
|
||||
@@ -81,11 +81,11 @@ class SubscribeQueryOwner(_SubscribeOwnerBase):
|
||||
def get_subscribed_sites(self, mtype: Optional[str] = None) -> Optional[List[int]]:
|
||||
"""
|
||||
获取指定媒体类型订阅涉及的站点清单(节约资源)
|
||||
未指定媒体类型时保持原有全量订阅行为;指定类型却没有可搜索订阅时返回 None,
|
||||
指定范围没有可搜索订阅时返回 None,包括全局订阅全部暂停或尚未开始的情况,
|
||||
避免调用方把空站点误解为“搜索所有站点”。
|
||||
|
||||
:param mtype: 可选媒体类型
|
||||
:return: 返回[]代表所有站点命中,返回None代表没有订阅
|
||||
:return: 返回 [] 代表有效订阅沿用默认或全部站点,None 代表没有可搜索订阅
|
||||
"""
|
||||
ret_sites = []
|
||||
subscribes = self.subscription_repository.list()
|
||||
@@ -102,7 +102,7 @@ class SubscribeQueryOwner(_SubscribeOwnerBase):
|
||||
if ret_sites:
|
||||
ret_sites = list(set(ret_sites))
|
||||
|
||||
if mtype is not None and not has_searchable_subscription:
|
||||
if not has_searchable_subscription:
|
||||
return None
|
||||
|
||||
return ret_sites
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
订阅元数据、进度与剧集范围刷新
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from dataclasses import replace
|
||||
from datetime import datetime
|
||||
from threading import Event
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast
|
||||
|
||||
from app.application.configuration import get_scheduler_runtime_config
|
||||
from app.application.subscription import priority as _priority
|
||||
from app.application.subscription.activity import activity_time, subscription_activity_scope
|
||||
from app.application.subscription.contract import (
|
||||
@@ -16,10 +19,12 @@ from app.application.subscription.contract import (
|
||||
)
|
||||
from app.application.subscription.facts import FreshFactLease
|
||||
from app.application.subscription.observability import subscription_log_scope
|
||||
from app.application.subscription.refresh import RefreshPolicy
|
||||
from app.chain.download import DownloadChain
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.subscribe.identity import subscribe_recognize_kwargs
|
||||
from app.chain.subscribe.metadata import SubscribeMetadataOwner
|
||||
from app.chain.subscribe.poll import SubscriptionRefreshPoll
|
||||
from app.chain.tmdb import TmdbChain
|
||||
from app.chain.torrents import TorrentsChain
|
||||
from app.domain.context import (
|
||||
@@ -27,8 +32,10 @@ from app.domain.context import (
|
||||
)
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.runtime.events import eventmanager
|
||||
from app.runtime.execution import await_task_to_terminal
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.stop import runtime_stop_state
|
||||
from app.runtime.tasks import get_task_registry
|
||||
from app.schemas.event import SubscribeEpisodesRefreshEventData
|
||||
from app.schemas.mediaserver import NotExistMediaInfo as _SchemaNotExistMediaInfo
|
||||
from app.schemas.types import (
|
||||
@@ -43,12 +50,38 @@ class SubscribeRefreshOwner(SubscribeMetadataOwner):
|
||||
订阅元数据、进度与剧集范围刷新,作为 SubscribeChain 的单一职责组件。
|
||||
"""
|
||||
|
||||
async def async_refresh(
|
||||
self, progress_callback: Optional[Callable[..., None]] = None, *,
|
||||
mtype: Optional[str] = None, source: str = "automatic", scheduled: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
托管同步刷新工作,取消或配置重载后仍等真实收尾才交还调度所有权。
|
||||
|
||||
:param progress_callback: 传递到刷新、匹配和排程进度的回调
|
||||
:param mtype: 手工刷新可选的媒体类型
|
||||
:param source: 活动记录来源,手工入口使用 manual
|
||||
:param scheduled: 是否只处理自动模式下已到期站点
|
||||
"""
|
||||
stop_event = Event()
|
||||
task = get_task_registry().create_sync(
|
||||
self.refresh, owner="subscription.refresh", progress_callback=progress_callback,
|
||||
mtype=mtype, source=source, scheduled=scheduled, _stop_event=stop_event,
|
||||
)
|
||||
try:
|
||||
await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
stop_event.set()
|
||||
await await_task_to_terminal(task)
|
||||
raise
|
||||
|
||||
def refresh(
|
||||
self,
|
||||
progress_callback: Optional[Callable[..., None]] = None,
|
||||
*,
|
||||
mtype: Optional[str] = None,
|
||||
source: str = "automatic",
|
||||
scheduled: bool = False,
|
||||
_stop_event: Optional[Event] = None,
|
||||
) -> None:
|
||||
"""
|
||||
刷新指定媒体类型的订阅
|
||||
@@ -56,6 +89,8 @@ class SubscribeRefreshOwner(SubscribeMetadataOwner):
|
||||
:param progress_callback: 定时服务进度更新回调
|
||||
:param mtype: 可选媒体类型,省略时刷新所有类型
|
||||
:param source: 手工入口传 manual,定时和兼容调用默认 automatic
|
||||
:param scheduled: 自动模式的定时扫描按站点时间片运行;手工和旧插件缺省立即刷新
|
||||
:param _stop_event: 异步宿主取消本轮时停止接纳新站点,等待已接受工作真实结束
|
||||
"""
|
||||
# 触发刷新站点资源,从缓存中匹配订阅
|
||||
sites = self.get_subscribed_sites(mtype)
|
||||
@@ -64,6 +99,11 @@ class SubscribeRefreshOwner(SubscribeMetadataOwner):
|
||||
progress_callback(value=100, text="没有订阅需要刷新")
|
||||
return
|
||||
|
||||
if scheduled and self.runtime_config.subscribe_mode == "spider":
|
||||
policy = RefreshPolicy(timezone_name=get_scheduler_runtime_config().timezone)
|
||||
SubscriptionRefreshPoll(self, policy, progress_callback, _stop_event).run()
|
||||
return
|
||||
|
||||
def _update_refresh_progress(
|
||||
value: Optional[float] = None,
|
||||
text: Optional[str] = None,
|
||||
|
||||
@@ -3,15 +3,19 @@
|
||||
"""
|
||||
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from typing import Any, Callable, Dict, List, Optional, Union, cast
|
||||
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.rss import RssHelper
|
||||
from app.application.site.observation import SiteSearchObservation, capture_site_search_observation
|
||||
from app.application.site.protocol import site_domain, torrent_resource_identity
|
||||
|
||||
# 站点资源包在启动时加载,静态检查环境可能无法解析其实现。
|
||||
from app.application.site.sites import SitesHelper # pylint: disable=import-error,no-name-in-module
|
||||
from app.application.site.throttle import site_request_cooldown
|
||||
from app.application.subscription.candidates import CandidateIndex
|
||||
from app.application.subscription.contract import SubscriptionSnapshot
|
||||
from app.application.torrent.download import TorrentHelper
|
||||
@@ -32,9 +36,15 @@ from app.schemas.types import MediaType, MessageType, NotificationChannel, Syste
|
||||
|
||||
class TorrentsChain(ChainBase):
|
||||
"""
|
||||
站点首页或RSS种子处理链,服务于订阅、刷流等
|
||||
站点首页或RSS种子处理链,服务于订阅、刷流等。
|
||||
|
||||
:cvar _refresh_sites_lock: 保护站点刷新准入集合的进程锁
|
||||
:cvar _refreshing_sites: 仍在抓取或识别的站点,真实结束前不释放
|
||||
"""
|
||||
|
||||
_refresh_sites_lock = threading.Lock()
|
||||
_refreshing_sites: set[int] = set()
|
||||
|
||||
_spider_file = "__torrents_cache__"
|
||||
_rss_file = "__rss_cache__"
|
||||
# 音乐资源独立缓存,与影视种子分开计算配额与存储,避免被影视资源挤出
|
||||
@@ -439,13 +449,16 @@ class TorrentsChain(ChainBase):
|
||||
self,
|
||||
domain: str,
|
||||
torrents: List[TorrentInfo],
|
||||
observations: list[SiteSearchObservation],
|
||||
) -> List[TorrentInfo]:
|
||||
"""
|
||||
追加抓取站点音乐专用入口的最新种子,并按种子链接去重后返回合并结果。
|
||||
追加音乐专用入口并去重,逐页保存请求事实,避免后页限流抹掉前页的真实请求。
|
||||
"""
|
||||
seen = {torrent.enclosure for torrent in torrents if torrent.enclosure}
|
||||
for page in range(2):
|
||||
page_torrents = self.browse(domain=domain, page=page, mtype=MediaType.MUSIC)
|
||||
with capture_site_search_observation() as observation:
|
||||
page_torrents = self.browse(domain=domain, page=page, mtype=MediaType.MUSIC)
|
||||
observations.append(observation)
|
||||
if not page_torrents:
|
||||
# 某一页没有数据,说明已经到最后一页,停止获取
|
||||
break
|
||||
@@ -457,64 +470,123 @@ class TorrentsChain(ChainBase):
|
||||
torrents.append(torrent)
|
||||
return torrents
|
||||
|
||||
def _refresh_indexer(
|
||||
self,
|
||||
indexer: dict[str, Any],
|
||||
stype: str,
|
||||
include_music: bool,
|
||||
torrents_cache: Dict[str, List[Context]],
|
||||
music_cache: Dict[str, List[Context]],
|
||||
) -> str:
|
||||
def _fetch_refresh_resources(
|
||||
self, indexer: dict[str, Any], stype: str, include_music: bool,
|
||||
) -> tuple[List[TorrentInfo], dict[str, object]]:
|
||||
"""
|
||||
抓取并写入单个站点的影视、音乐资源缓存。
|
||||
在共享缓存锁外抓取站点页面,区分成功空页、失败和未发请求的限流。
|
||||
"""
|
||||
domain = site_domain(indexer.get("domain"))
|
||||
if stype == "spider":
|
||||
torrents: List[TorrentInfo] = []
|
||||
for page in range(2):
|
||||
page_torrents = self.browse(domain=domain, page=page)
|
||||
if not page_torrents:
|
||||
break
|
||||
torrents.extend(page_torrents)
|
||||
else:
|
||||
torrents = self.rss(domain=domain)
|
||||
if include_music and self._music_browse_paths(indexer):
|
||||
torrents = self.__append_music_browse_torrents(domain=domain, torrents=torrents)
|
||||
torrents.sort(key=lambda item: item.pubdate or "", reverse=True)
|
||||
music_torrents = [
|
||||
item for item in torrents if item.category == MediaType.MUSIC.value
|
||||
][:self.runtime_config.refresh_batch_size]
|
||||
torrents = [
|
||||
item for item in torrents if item.category != MediaType.MUSIC.value
|
||||
][:self.runtime_config.refresh_batch_size]
|
||||
if not torrents and not music_torrents:
|
||||
logger.info(f'{indexer.get("name")} 没有获取到种子')
|
||||
return domain
|
||||
if self._is_no_cache_site(domain):
|
||||
logger.info(
|
||||
f'{indexer.get("name")} 有 {len(torrents) + len(music_torrents)} 个种子 (不缓存)'
|
||||
)
|
||||
torrents_cache[domain] = []
|
||||
music_cache[domain] = []
|
||||
else:
|
||||
torrents = self._refresh_cached_torrents(torrents, torrents_cache.setdefault(domain, []))
|
||||
music_torrents = self._refresh_cached_torrents(music_torrents, music_cache.setdefault(domain, []))
|
||||
if not torrents and not music_torrents:
|
||||
logger.info(f'{indexer.get("name")} 没有新种子')
|
||||
return domain
|
||||
logger.info(f'{indexer.get("name")} 有 {len(torrents) + len(music_torrents)} 个新种子')
|
||||
for torrent in torrents + music_torrents:
|
||||
if runtime_stop_state.is_system_stopped:
|
||||
torrents: List[TorrentInfo] = []
|
||||
observations = []
|
||||
for page in range(2 if stype == "spider" else 1):
|
||||
with capture_site_search_observation() as observation:
|
||||
page_torrents = self.browse(domain=domain, page=page) if stype == "spider" else self.rss(domain=domain)
|
||||
observations.append(observation)
|
||||
torrents.extend(page_torrents)
|
||||
if not page_torrents or runtime_stop_state.is_system_stopped:
|
||||
break
|
||||
if not torrent.enclosure:
|
||||
logger.warning(f"缺少种子链接,忽略处理: {torrent.title}")
|
||||
continue
|
||||
context = self._build_refresh_context(torrent, stype)
|
||||
target_cache = music_cache if torrent.category == MediaType.MUSIC.value else torrents_cache
|
||||
target_cache.setdefault(domain, []).append(context)
|
||||
if len(target_cache[domain]) > self.runtime_config.torrent_cache_size:
|
||||
target_cache[domain] = target_cache[domain][-self.runtime_config.torrent_cache_size:]
|
||||
return domain
|
||||
if include_music and self._music_browse_paths(indexer) and not runtime_stop_state.is_system_stopped:
|
||||
torrents = self.__append_music_browse_torrents(domain, torrents, observations)
|
||||
reported = [item for item in observations if item.outcome != "skipped"]
|
||||
# RSS 和旧插件不报告观察事实时保留未知,不把空列表当作成功。
|
||||
outcome = "success" if torrents else "unknown"
|
||||
if reported:
|
||||
outcome = next((item.outcome for item in reported if item.outcome != "success"), "success")
|
||||
fact: dict[str, object] = {
|
||||
"id": indexer.get("id"), "name": indexer.get("name"), "status": outcome,
|
||||
"attempted": any(item.attempted for item in reported) if reported else True,
|
||||
"retry_after": max(60.0, site_request_cooldown(indexer)),
|
||||
}
|
||||
return torrents, fact
|
||||
|
||||
def _refresh_site_cache(self, domain: str, stype: str) -> tuple[Dict[str, List[Context]], Dict[str, List[Context]]]:
|
||||
"""
|
||||
在调用方持有短缓存锁时读取最新快照,仅清理本次站点的无效资源。
|
||||
"""
|
||||
video_file, music_file = self._cache_file_pair(stype)
|
||||
video, music = self.load_cache(video_file) or {}, self.load_cache(music_file) or {}
|
||||
for cache in (video, music):
|
||||
self._ensure_context_compatibility(cache, stype=stype)
|
||||
cache[domain] = [context for context in cache.get(domain, []) if context.torrent_info
|
||||
and not TorrentHelper().is_invalid(context.torrent_info.enclosure)]
|
||||
return video, music
|
||||
|
||||
def _select_refresh_resources(self, torrents: List[TorrentInfo]) -> tuple[List[TorrentInfo], List[TorrentInfo]]:
|
||||
"""
|
||||
保持影视与音乐各自的处理配额,并优先处理新发布资源。
|
||||
"""
|
||||
torrents.sort(key=lambda item: item.pubdate or "", reverse=True)
|
||||
video = [item for item in torrents if item.category != MediaType.MUSIC.value]
|
||||
music = [item for item in torrents if item.category == MediaType.MUSIC.value]
|
||||
return video[:self.runtime_config.refresh_batch_size], music[:self.runtime_config.refresh_batch_size]
|
||||
|
||||
def _commit_refresh_resources(
|
||||
self, domain: str, stype: str, resources: tuple[List[TorrentInfo], List[TorrentInfo]],
|
||||
prepared: dict[tuple[object, ...], Context],
|
||||
) -> List[Context]:
|
||||
"""
|
||||
重新读取并合并单站快照,保留并行站点写入及期间人工修正的识别结果。
|
||||
"""
|
||||
with cache_mutation("torrent-snapshots"):
|
||||
caches = self._refresh_site_cache(domain, stype)
|
||||
for cache, torrents in zip(caches, resources):
|
||||
if self._is_no_cache_site(domain) and any(resources):
|
||||
cache[domain] = []
|
||||
for torrent in self._refresh_cached_torrents(torrents, cache[domain]):
|
||||
context = prepared.get(self._torrent_cache_key(torrent))
|
||||
if context is not None:
|
||||
cache[domain].append(context)
|
||||
cache[domain] = cache[domain][-self.runtime_config.torrent_cache_size:]
|
||||
for cache, filename in zip(caches, self._cache_file_pair(stype)):
|
||||
self.save_cache(cache, filename, strict=True)
|
||||
return list(caches[0][domain]) + list(caches[1][domain])
|
||||
|
||||
def refresh_site(
|
||||
self, indexer: dict[str, Any], stype: str = "spider", include_music: bool = False,
|
||||
) -> tuple[str, List[Context], dict[str, object]]:
|
||||
"""
|
||||
独占一个站点直至抓取、识别和缓存合并真实结束,其他站点可同时处理。
|
||||
|
||||
网络和媒体识别不持有共享缓存锁;只在读取与合并时短暂持锁。
|
||||
|
||||
:param indexer: 已选择的站点索引配置,不写入排程快照或日志
|
||||
:param stype: 缓存与抓取模式,spider 或 rss
|
||||
:param include_music: 是否追加音乐专用入口
|
||||
:return: 站点域名、该站最新共享候选和不含凭据的执行事实
|
||||
"""
|
||||
site_id = int(indexer["id"])
|
||||
domain = site_domain(indexer.get("domain"))
|
||||
with self._refresh_sites_lock:
|
||||
busy = site_id in self._refreshing_sites
|
||||
if not busy:
|
||||
self._refreshing_sites.add(site_id)
|
||||
if busy:
|
||||
with cache_mutation("torrent-snapshots"):
|
||||
caches = self._refresh_site_cache(domain, stype)
|
||||
return domain, list(caches[0][domain]) + list(caches[1][domain]), {
|
||||
"id": site_id, "name": indexer.get("name"),
|
||||
"status": "deferred", "attempted": False, "retry_after": 60,
|
||||
}
|
||||
started = time.monotonic()
|
||||
try:
|
||||
torrents, fact = self._fetch_refresh_resources(indexer, stype, include_music)
|
||||
resources = self._select_refresh_resources(torrents)
|
||||
with cache_mutation("torrent-snapshots"):
|
||||
caches = self._refresh_site_cache(domain, stype)
|
||||
prepared: dict[tuple[object, ...], Context] = {}
|
||||
for cache, items in zip(caches, resources):
|
||||
cached = [] if self._is_no_cache_site(domain) else cache[domain]
|
||||
for torrent in self._refresh_cached_torrents(items, cached):
|
||||
if runtime_stop_state.is_system_stopped:
|
||||
break
|
||||
prepared[self._torrent_cache_key(torrent)] = self._build_refresh_context(torrent, stype)
|
||||
contexts = self._commit_refresh_resources(domain, stype, resources, prepared)
|
||||
fact.update(candidates=len(contexts), new_candidates=len(prepared), seconds=time.monotonic() - started)
|
||||
return domain, contexts, fact
|
||||
finally:
|
||||
with self._refresh_sites_lock:
|
||||
self._refreshing_sites.remove(site_id)
|
||||
|
||||
@staticmethod
|
||||
def _torrent_cache_key(torrent: TorrentInfo) -> tuple[object, ...]:
|
||||
@@ -606,7 +678,6 @@ class TorrentsChain(ChainBase):
|
||||
context.media_recognize_fail_count = 1
|
||||
return context
|
||||
|
||||
@cache_mutation("torrent-snapshots")
|
||||
def refresh(
|
||||
self,
|
||||
stype: Optional[str] = None,
|
||||
@@ -616,96 +687,42 @@ class TorrentsChain(ChainBase):
|
||||
site_observer: Optional[Callable[[dict[str, object]], None]] = None,
|
||||
) -> Dict[str, List[Context]]:
|
||||
"""
|
||||
刷新站点最新资源并返回本轮可匹配的完整候选缓存。
|
||||
刷新所选站点并合并共享候选,保留手工及插件入口的同步调用合同。
|
||||
|
||||
:param stype: 强制指定缓存类型,spider:爬虫缓存,rss:rss缓存
|
||||
:param sites: 强制指定站点ID列表,为空则读取设置的订阅站点
|
||||
:param progress_callback: 资源刷新进度更新回调
|
||||
:param include_music: 是否额外抓取站点的音乐专用浏览入口,服务音乐订阅
|
||||
:param site_observer: 输出已检查站点和安全候选计数,不以空列表推断请求成功
|
||||
:param stype: 强制指定 spider 或 rss,缺省使用当前订阅模式
|
||||
:param sites: 所选站点;空列表沿用默认订阅站点或全部站点的兼容语义
|
||||
:param progress_callback: 每个站点完成后更新进度
|
||||
:param include_music: 是否追加音乐专用入口
|
||||
:param site_observer: 接收各站点的请求、结果和候选事实
|
||||
:return: 本次所选站点的最新共享候选
|
||||
"""
|
||||
if not stype:
|
||||
stype = self.runtime_config.subscribe_mode
|
||||
|
||||
if not sites:
|
||||
sites = get_configured_system_config().get(SystemConfigKey.RssSites) or []
|
||||
|
||||
# 读取缓存,影视与音乐分别独立存储
|
||||
if stype == 'spider':
|
||||
torrents_cache = self.load_cache(self._spider_file) or {}
|
||||
music_cache = self.load_cache(self._music_spider_file) or {}
|
||||
else:
|
||||
torrents_cache = self.load_cache(self._rss_file) or {}
|
||||
music_cache = self.load_cache(self._music_rss_file) or {}
|
||||
self._ensure_context_compatibility(torrents_cache, stype=stype)
|
||||
self._ensure_context_compatibility(music_cache, stype=stype)
|
||||
|
||||
# 缓存过滤掉无效种子(影视与音乐缓存分别处理)
|
||||
for _cache in (torrents_cache, music_cache):
|
||||
for _domain, _torrents in _cache.items():
|
||||
_cache[_domain] = [_torrent for _torrent in _torrents
|
||||
if not TorrentHelper().is_invalid(_torrent.torrent_info.enclosure)]
|
||||
|
||||
domains = []
|
||||
indexers = [
|
||||
indexer for indexer in SitesHelper().get_indexers()
|
||||
if not sites or indexer.get("id") in sites
|
||||
]
|
||||
total_indexers = len(indexers)
|
||||
if progress_callback:
|
||||
progress_callback(
|
||||
value=0,
|
||||
text=f"开始刷新站点资源,共 {total_indexers} 个站点 ...",
|
||||
data={"total": total_indexers, "finished": 0},
|
||||
)
|
||||
stype = self._cache_type(stype)
|
||||
indexers = self.refresh_indexers(sites)
|
||||
candidates: Dict[str, List[Context]] = {}
|
||||
for index, indexer in enumerate(indexers, start=1):
|
||||
if runtime_stop_state.is_system_stopped:
|
||||
break
|
||||
if progress_callback:
|
||||
progress_callback(
|
||||
value=(index - 1) / total_indexers * 100 if total_indexers else 100,
|
||||
text=f"正在刷新站点资源({index}/{total_indexers}){indexer.get('name')} ...",
|
||||
data={
|
||||
"total": total_indexers,
|
||||
"finished": index - 1,
|
||||
"current": indexer.get("id"),
|
||||
},
|
||||
)
|
||||
domain = self._refresh_indexer(
|
||||
indexer=indexer, stype=stype, include_music=include_music,
|
||||
torrents_cache=torrents_cache, music_cache=music_cache,
|
||||
)
|
||||
domains.append(domain)
|
||||
progress_callback(value=(index - 1) / len(indexers) * 100,
|
||||
text=f"正在刷新站点资源({index}/{len(indexers)}){indexer.get('name')} ...",
|
||||
data={"total": len(indexers), "finished": index - 1, "current": indexer.get("id")})
|
||||
domain, contexts, fact = self.refresh_site(indexer, stype, include_music)
|
||||
candidates[domain] = contexts
|
||||
if site_observer:
|
||||
site_observer({"id": indexer.get("id"), "name": indexer.get("name"),
|
||||
"candidates": len(torrents_cache.get(domain, [])) + len(music_cache.get(domain, [])),
|
||||
"status": "checked"})
|
||||
|
||||
# 保存缓存到本地,影视与音乐分别存储
|
||||
if stype == "spider":
|
||||
self.save_cache(torrents_cache, self._spider_file)
|
||||
self.save_cache(music_cache, self._music_spider_file)
|
||||
else:
|
||||
self.save_cache(torrents_cache, self._rss_file)
|
||||
self.save_cache(music_cache, self._music_rss_file)
|
||||
|
||||
# 去除不在站点范围内的缓存种子
|
||||
if sites and torrents_cache:
|
||||
torrents_cache = {k: v for k, v in torrents_cache.items() if k in domains}
|
||||
if sites and music_cache:
|
||||
music_cache = {k: v for k, v in music_cache.items() if k in domains}
|
||||
|
||||
site_observer(fact)
|
||||
if progress_callback:
|
||||
progress_callback(
|
||||
value=100,
|
||||
text="站点资源刷新完成",
|
||||
data={"total": total_indexers, "finished": total_indexers},
|
||||
)
|
||||
progress_callback(value=100, text="站点资源刷新完成",
|
||||
data={"total": len(indexers), "finished": len(candidates)})
|
||||
return candidates
|
||||
|
||||
return self._merge_torrent_caches(
|
||||
{domain: list(contexts) for domain, contexts in torrents_cache.items()},
|
||||
music_cache,
|
||||
)
|
||||
@staticmethod
|
||||
def refresh_indexers(sites: Optional[List[int]]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
解析刷新入口共享的有效站点范围,空列表保留默认站点兼容语义。
|
||||
"""
|
||||
if not sites:
|
||||
sites = get_configured_system_config().get(SystemConfigKey.RssSites) or []
|
||||
return [indexer for indexer in SitesHelper().get_indexers() if not sites or indexer.get("id") in sites]
|
||||
|
||||
@staticmethod
|
||||
def _ensure_context_compatibility(
|
||||
|
||||
@@ -76,6 +76,8 @@ METRIC_SPECS = {
|
||||
MetricSpec("scheduler.job.overlap_skip", MetricKind.COUNTER, frozenset({"owner"})),
|
||||
MetricSpec("scheduler.job.retry", MetricKind.COUNTER, frozenset({"owner"})),
|
||||
MetricSpec("scheduler.job.dead_letter", MetricKind.COUNTER, frozenset({"owner"})),
|
||||
MetricSpec("subscription.refresh.site", MetricKind.COUNTER, frozenset({"owner", "outcome"})),
|
||||
MetricSpec("subscription.refresh.site.duration", MetricKind.HISTOGRAM, frozenset({"owner"})),
|
||||
MetricSpec("plugin.lifecycle.duration", MetricKind.HISTOGRAM, frozenset({"operation", "outcome"})),
|
||||
MetricSpec("agent.active_tasks", MetricKind.GAUGE, frozenset({"task_type"})),
|
||||
MetricSpec("agent.chat.persistence.pending", MetricKind.GAUGE, frozenset()),
|
||||
|
||||
@@ -217,6 +217,13 @@ class SchedulerCatalogOwner(_SchedulerOwnerBase):
|
||||
next_run_time=datetime.now(pytz.timezone(config.timezone)) + timedelta(seconds=5),
|
||||
)
|
||||
|
||||
def _poll_subscription_refresh(self) -> None:
|
||||
"""
|
||||
刷新空闲时才唤醒托管任务,在途扫描会合并到期站点,不重复报告重入。
|
||||
"""
|
||||
if not self._is_job_active("subscribe_refresh"):
|
||||
self.start("subscribe_refresh", scheduled=True)
|
||||
|
||||
def _initialize_catalog(self, config: SchedulerRuntimeConfig) -> None:
|
||||
"""
|
||||
构建完整任务目录并投影到尚未启动的 APScheduler。
|
||||
@@ -229,7 +236,7 @@ class SchedulerCatalogOwner(_SchedulerOwnerBase):
|
||||
JobSpec("mediaserver_sync", "同步媒体服务器", services.sync_mediaserver, "mediaserver"),
|
||||
JobSpec("subscribe_tmdb", "订阅元数据更新", services.check_subscribe, "subscription"),
|
||||
*_subscription_search_job_specs(services, config.subscribe_search_interval),
|
||||
JobSpec("subscribe_refresh", "订阅刷新", services.refresh_subscribe, "subscription"),
|
||||
JobSpec("subscribe_refresh", "订阅刷新", services.refresh_subscribe, "subscription", timeout_seconds=0),
|
||||
JobSpec("subscribe_follow", "关注的订阅分享", services.follow_subscribe, "subscription"),
|
||||
JobSpec(
|
||||
"transfer",
|
||||
@@ -378,18 +385,15 @@ class SchedulerCatalogOwner(_SchedulerOwnerBase):
|
||||
)
|
||||
|
||||
if config.subscribe_mode == "spider":
|
||||
# 站点首页种子定时刷新模式
|
||||
triggers = TimerUtils.random_scheduler(num_executions=32)
|
||||
for trigger in triggers:
|
||||
self._scheduler.add_job(
|
||||
self.start,
|
||||
"cron",
|
||||
id=f"subscribe_refresh|{trigger.hour}:{trigger.minute}",
|
||||
name="订阅刷新",
|
||||
hour=trigger.hour,
|
||||
minute=trigger.minute,
|
||||
kwargs={"job_id": "subscribe_refresh"},
|
||||
)
|
||||
# 轻量检查逐站到期时间;实际请求受持久时间片和站点限流共同约束。
|
||||
self._scheduler.add_job(
|
||||
self._poll_subscription_refresh,
|
||||
"interval",
|
||||
id="subscribe_refresh",
|
||||
name="订阅刷新",
|
||||
minutes=1,
|
||||
next_run_time=datetime.now(pytz.timezone(config.timezone)) + timedelta(seconds=15),
|
||||
)
|
||||
else:
|
||||
# RSS订阅模式
|
||||
self._scheduler.add_job(
|
||||
|
||||
@@ -76,7 +76,7 @@ def configure_scheduler_services() -> None:
|
||||
check_subscribe=subscribe_chain.check_and_reconcile,
|
||||
search_subscribe=subscribe_chain.search,
|
||||
resume_subscribe_search=subscribe_chain.async_resume_search_queue,
|
||||
refresh_subscribe=subscribe_chain.refresh,
|
||||
refresh_subscribe=subscribe_chain.async_refresh,
|
||||
follow_subscribe=subscribe_chain.follow,
|
||||
process_transfer=transfer_chain.process,
|
||||
clear_cache=scheduler_chain.clear_cache,
|
||||
|
||||
@@ -558,6 +558,10 @@ flowchart TB
|
||||
I -->|是| J["标记完成 / 发送完成通知"]
|
||||
```
|
||||
|
||||
自动订阅刷新使用逐站时间片:Scheduler 每分钟唤醒到期检查,
|
||||
`application/subscription/refresh.py` 保存可恢复的排程事实,`chain/subscribe/poll.py` 持有有限在途工作,
|
||||
`chain/torrents.py` 在网络与识别完成后以短锁合并缓存。完整规则见[自动订阅刷新排程](subscription-refresh.md)。
|
||||
|
||||
### 6.3 文件整理(Transfer)与监控
|
||||
|
||||
```mermaid
|
||||
@@ -836,8 +840,8 @@ flowchart LR
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1164 |
|
||||
| 内部导入边 | 10,136 |
|
||||
| Python 模块 | 1166 |
|
||||
| 内部导入边 | 10,159 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) |
|
||||
|
||||
@@ -115,6 +115,12 @@ Entrypoints (app/api, app/command, app/monitor, app/scheduler, app/agent, app/wo
|
||||
`search/`, `media/`) keep class identity and event wrappers on `facade.py` and
|
||||
isolate queue, planning, execution, settlement and cache adapters in
|
||||
single-word owner modules, and retired single-file monoliths must not return.
|
||||
- Automatic subscription refresh policy and restartable time-slot facts belong
|
||||
to `application/subscription/refresh.py`; `chain/subscribe/poll.py` owns the
|
||||
finite set of in-flight site futures through real completion, and
|
||||
`chain/torrents.py` owns per-site fetch/recognition and short cache merges.
|
||||
Scheduler only wakes the injected refresh callable; it does not create a
|
||||
separate business worker pool or own a second refresh queue.
|
||||
|
||||
### Module and Agent Layer
|
||||
|
||||
|
||||
52
docs/subscription-refresh.md
Normal file
52
docs/subscription-refresh.md
Normal file
@@ -0,0 +1,52 @@
|
||||
# 自动订阅刷新排程
|
||||
|
||||
自动模式(`SUBSCRIBE_MODE=spider`)每分钟检查一次站点是否到期,只对到期站点抓取首页。
|
||||
每分钟扫描不是每分钟访问站点;没有可搜索订阅、全部暂停或尚未开始时,不抓取默认站点。
|
||||
|
||||
## 时间分配
|
||||
|
||||
每个站点每天分配 36 个时间片,按系统配置的时区计算:
|
||||
|
||||
| 时段 | 时间片数 | 分配方式 |
|
||||
| --- | ---: | --- |
|
||||
| 07:00–23:00 | 32 | 每片 30 分钟,片内错开请求 |
|
||||
| 23:00–次日 07:00 | 4 | 每片约 2 小时,片内错开请求 |
|
||||
|
||||
请求时间取在每片中间的 40% 范围。白天计划间隔为 18–42 分钟;实际访问仍保留至少 20 分钟间隔。
|
||||
普通 24 小时排程日的最长计划间隔约为 168 分钟,
|
||||
覆盖夜间;夏令时切换日按真实时间均分夜间。站点、日期和实例使用不同偏移,重启不重新抽签。
|
||||
初次启用或新增站点在五分钟内错开首次检查,首次补查可能比当天分配的时间片多一次。
|
||||
正常分钟扫描最多增加一分钟唤醒延迟;线程池排队、站点流控和抓取耗时也会推迟实际完成。
|
||||
|
||||
每次仍按原有分页范围抓取:普通首页最多两页;有音乐订阅且站点有独立音乐入口时,
|
||||
该入口最多再抓两页。36 个时间片是刷新次数,不能理解为 36 次 HTTP 请求。
|
||||
|
||||
## 并发、流控和恢复
|
||||
|
||||
自动刷新使用现有共享线程池,最多同时处理两个站点,同一站点在真实工作退出前始终互斥。
|
||||
抓取和媒体识别不持有整份资源缓存锁,写入时短暂加锁、重读并合并当前站点,保留其他站点写入
|
||||
和期间人工修正的识别结果。健康站点完成后可先从全部有效站点的共享候选中匹配订阅。
|
||||
首次结果立即匹配,之后五分钟内的站点结果合并处理,避免每个站点完成都重复扫描全部订阅。
|
||||
待匹配标记与站点安全结果计数一起保存,合并窗口跨越重启也不会丢失。
|
||||
|
||||
任务尚在运行时,每 30 秒或每次站点完成后继续检查到期工作。错过多个时间片只合并一次机会,
|
||||
不会补发停机期间的历史请求。实际访问之间至少间隔 20 分钟;失败按站点退避,最多退避两小时,
|
||||
站点返回的更长冷却时间继续生效。未发出请求的流控延后不消耗时间片,成功空页会清零失败计数。
|
||||
所有请求仍经过站点原有的共享流控入口。
|
||||
|
||||
排程缓存 `__subscribe_refresh_schedule__` 保存实例随机盐、站点时间片、失败及结果计数和未完成匹配标记,
|
||||
不保存凭据、资源内容或线程。热重载和重启沿用这些事实;抓取后匹配失败可从资源缓存继续匹配。
|
||||
排程不是下载队列,也不提供跨进程租约;硬断电时尚未保存的抓取事实可能在恢复后重查一次。
|
||||
正常关闭、取消和异常收尾等待已接受的同步线程真实退出,再释放调度所有权。
|
||||
|
||||
手工刷新保持立即执行所选站点的行为;RSS 模式继续使用配置的 RSS 周期,主动搜索仍使用独立的
|
||||
订阅搜索周期。自动排程的内部默认值不增加用户配置项。
|
||||
|
||||
## 诊断和验证
|
||||
|
||||
调度进度提供 `finished`、`running_sites` 和 `next_refresh_at`;站点实际结果进入订阅刷新活动。
|
||||
`subscription.refresh.site` 按结果计数,`subscription.refresh.site.duration` 记录单站耗时;
|
||||
指标不使用站点名、域名或订阅 ID 作为标签。
|
||||
|
||||
回归入口见[测试说明](testing.md#自动订阅刷新排程)。验证使用虚拟时间、合成站点、临时缓存和真实
|
||||
线程屏障,覆盖夜间、时区、冷却、慢站、缓存合并、匹配恢复以及停止所有权,不访问真实账号。
|
||||
@@ -247,6 +247,22 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)):
|
||||
和虚拟时钟覆盖秒级冷却下的连续恢复,验证剩余来源继续翻页、末页候选处理后正常收尾,
|
||||
且未收录缺集仍保留。新一轮搜索或缺集范围扩大时重新评估候选;旧检查点缺少该记录时兼容恢复。
|
||||
|
||||
### 自动订阅刷新排程
|
||||
|
||||
`tests/test_subscription_refresh_schedule.py` 使用虚拟时间验证每天 32 个白天与 4 个夜间时间片、
|
||||
跨日与夏令时、不同实例及站点偏移、启动错峰、漏触发合并、限流、失败退避和重启恢复。
|
||||
`tests/test_subscription_refresh_poll.py` 与 `tests/test_torrents_refresh_concurrency.py` 使用合成站点、
|
||||
真实线程屏障和隔离缓存,验证慢站不阻塞健康站点、同站互斥、并行缓存合并、人工识别修正保留、
|
||||
成功空页与失败区分、匹配失败恢复、五分钟匹配合并及跨轮次事实恢复,以及保存失败后仍等待已接受工作结束。
|
||||
`tests/test_scheduler_cache_expiry.py` 验证自动模式分钟扫描与 RSS 原周期,
|
||||
`tests/test_scheduler_lifecycle.py` 验证刷新取消后仍保留 Scheduler 所有权直至同步线程退出。
|
||||
这些用例不访问站点、下载器或真实数据库;不能替代真实站点的流控与响应验收。
|
||||
排程行为与持久化边界见[自动订阅刷新排程](subscription-refresh.md)。
|
||||
新增排程策略和轮询 owner 两个模块,因此三个启动入口的模块数快照各增加 2;
|
||||
仅更新该结构事实,原冷导入耗时记录与 3000ms 上限保留,生命周期组件集合及释放要求不变。
|
||||
|
||||
### 站点流控
|
||||
|
||||
本地流控等待由实际拒绝原因决定:访问间隔不足只等待间隔,计数配额耗尽才等待计数窗口。
|
||||
资源包说明包含上次访问时间时扣除已过去的时间,并保留一秒边界余量;原因未知时沿用保守窗口,
|
||||
时间缺失或无效时等待该规则全长。`tests/test_search_site_throttle.py`、`tests/test_search_scan.py`
|
||||
|
||||
@@ -963,8 +963,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10136,
|
||||
"edge_sha256": "3768338a92d10d7883a42acdb9eff190fa1cd0af9e68b7ae317c03d3ddbf3f9c",
|
||||
"edge_count": 10159,
|
||||
"edge_sha256": "b00d7edef6d49ece1f002dfef6f21b80a787959c08b60729c8b9a805d330c125",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -5823,6 +5823,22 @@
|
||||
"app.chain.subscribe.policy -> app.schemas",
|
||||
"app.chain.subscribe.policy -> app.schemas.mediaserver",
|
||||
"app.chain.subscribe.policy -> app.schemas.types",
|
||||
"app.chain.subscribe.poll -> app.application",
|
||||
"app.chain.subscribe.poll -> app.application.site",
|
||||
"app.chain.subscribe.poll -> app.application.site.protocol",
|
||||
"app.chain.subscribe.poll -> app.application.subscription",
|
||||
"app.chain.subscribe.poll -> app.application.subscription.refresh",
|
||||
"app.chain.subscribe.poll -> app.chain",
|
||||
"app.chain.subscribe.poll -> app.chain.subscribe",
|
||||
"app.chain.subscribe.poll -> app.chain.subscribe.contract",
|
||||
"app.chain.subscribe.poll -> app.chain.torrents",
|
||||
"app.chain.subscribe.poll -> app.domain",
|
||||
"app.chain.subscribe.poll -> app.domain.context",
|
||||
"app.chain.subscribe.poll -> app.runtime",
|
||||
"app.chain.subscribe.poll -> app.runtime.log",
|
||||
"app.chain.subscribe.poll -> app.runtime.observability",
|
||||
"app.chain.subscribe.poll -> app.runtime.stop",
|
||||
"app.chain.subscribe.poll -> app.runtime.thread",
|
||||
"app.chain.subscribe.query -> app.application",
|
||||
"app.chain.subscribe.query -> app.application.configuration",
|
||||
"app.chain.subscribe.query -> app.application.mediaserver",
|
||||
@@ -5857,18 +5873,21 @@
|
||||
"app.chain.subscribe.reconcile -> app.schemas",
|
||||
"app.chain.subscribe.reconcile -> app.schemas.types",
|
||||
"app.chain.subscribe.refresh -> app.application",
|
||||
"app.chain.subscribe.refresh -> app.application.configuration",
|
||||
"app.chain.subscribe.refresh -> app.application.subscription",
|
||||
"app.chain.subscribe.refresh -> app.application.subscription.activity",
|
||||
"app.chain.subscribe.refresh -> app.application.subscription.contract",
|
||||
"app.chain.subscribe.refresh -> app.application.subscription.facts",
|
||||
"app.chain.subscribe.refresh -> app.application.subscription.observability",
|
||||
"app.chain.subscribe.refresh -> app.application.subscription.priority",
|
||||
"app.chain.subscribe.refresh -> app.application.subscription.refresh",
|
||||
"app.chain.subscribe.refresh -> app.chain",
|
||||
"app.chain.subscribe.refresh -> app.chain.download",
|
||||
"app.chain.subscribe.refresh -> app.chain.media",
|
||||
"app.chain.subscribe.refresh -> app.chain.subscribe",
|
||||
"app.chain.subscribe.refresh -> app.chain.subscribe.identity",
|
||||
"app.chain.subscribe.refresh -> app.chain.subscribe.metadata",
|
||||
"app.chain.subscribe.refresh -> app.chain.subscribe.poll",
|
||||
"app.chain.subscribe.refresh -> app.chain.tmdb",
|
||||
"app.chain.subscribe.refresh -> app.chain.torrents",
|
||||
"app.chain.subscribe.refresh -> app.domain",
|
||||
@@ -5877,8 +5896,10 @@
|
||||
"app.chain.subscribe.refresh -> app.domain.meta.metabase",
|
||||
"app.chain.subscribe.refresh -> app.runtime",
|
||||
"app.chain.subscribe.refresh -> app.runtime.events",
|
||||
"app.chain.subscribe.refresh -> app.runtime.execution",
|
||||
"app.chain.subscribe.refresh -> app.runtime.log",
|
||||
"app.chain.subscribe.refresh -> app.runtime.stop",
|
||||
"app.chain.subscribe.refresh -> app.runtime.tasks",
|
||||
"app.chain.subscribe.refresh -> app.schemas",
|
||||
"app.chain.subscribe.refresh -> app.schemas.event",
|
||||
"app.chain.subscribe.refresh -> app.schemas.mediaserver",
|
||||
@@ -5958,7 +5979,9 @@
|
||||
"app.chain.torrents -> app.application.configuration",
|
||||
"app.chain.torrents -> app.application.rss",
|
||||
"app.chain.torrents -> app.application.site",
|
||||
"app.chain.torrents -> app.application.site.observation",
|
||||
"app.chain.torrents -> app.application.site.protocol",
|
||||
"app.chain.torrents -> app.application.site.throttle",
|
||||
"app.chain.torrents -> app.application.subscription",
|
||||
"app.chain.torrents -> app.application.subscription.candidates",
|
||||
"app.chain.torrents -> app.application.subscription.contract",
|
||||
@@ -11103,7 +11126,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1164,
|
||||
"module_count": 1166,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -11531,6 +11554,7 @@
|
||||
"app.application.subscription.observability",
|
||||
"app.application.subscription.priority",
|
||||
"app.application.subscription.query",
|
||||
"app.application.subscription.refresh",
|
||||
"app.application.subscription.search",
|
||||
"app.application.subscription.sitebudget",
|
||||
"app.application.subscription.status",
|
||||
@@ -11636,6 +11660,7 @@
|
||||
"app.chain.subscribe.music",
|
||||
"app.chain.subscribe.notify",
|
||||
"app.chain.subscribe.policy",
|
||||
"app.chain.subscribe.poll",
|
||||
"app.chain.subscribe.query",
|
||||
"app.chain.subscribe.reconcile",
|
||||
"app.chain.subscribe.refresh",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"repeat": 3,
|
||||
"targets": {
|
||||
"app.startup.lifecycle": {
|
||||
"loaded_app_module_count": 602,
|
||||
"loaded_app_module_count": 604,
|
||||
"max_ms": 1293.338,
|
||||
"median_ms": 1156.239,
|
||||
"min_ms": 1102.806,
|
||||
@@ -17,7 +17,7 @@
|
||||
]
|
||||
},
|
||||
"app.factory": {
|
||||
"loaded_app_module_count": 616,
|
||||
"loaded_app_module_count": 618,
|
||||
"max_ms": 1127.911,
|
||||
"median_ms": 1122.382,
|
||||
"min_ms": 1119.221,
|
||||
@@ -28,7 +28,7 @@
|
||||
]
|
||||
},
|
||||
"app.main": {
|
||||
"loaded_app_module_count": 618,
|
||||
"loaded_app_module_count": 620,
|
||||
"max_ms": 1188.652,
|
||||
"median_ms": 1183.509,
|
||||
"min_ms": 1174.522,
|
||||
|
||||
@@ -236,6 +236,9 @@ def test_refresh_include_music_fetches_music_entry():
|
||||
)
|
||||
|
||||
def _fake_browse(domain, keyword=None, cat=None, page=None, mtype=None):
|
||||
"""
|
||||
提供普通与音乐独立入口的合成分页,后页为空。
|
||||
"""
|
||||
if mtype == MediaType.MUSIC:
|
||||
# 第二页返回空,验证分页提前结束;首页返回音乐种子
|
||||
return [] if page else [music_torrent, duplicated_torrent]
|
||||
@@ -255,7 +258,7 @@ def test_refresh_include_music_fetches_music_entry():
|
||||
}]
|
||||
# 保存时对入参做快照,避免后续合并返回值修改同一字典引用
|
||||
saved = {}
|
||||
save_cache = Mock(side_effect=lambda data, filename: saved.__setitem__(filename, copy.deepcopy(data)))
|
||||
save_cache = Mock(side_effect=lambda data, filename, **_kwargs: saved.__setitem__(filename, copy.deepcopy(data)))
|
||||
|
||||
with (
|
||||
patch.object(chain, "load_cache", return_value=None),
|
||||
@@ -289,6 +292,7 @@ def test_refresh_include_music_fetches_music_entry():
|
||||
}
|
||||
assert video_titles == {"Some.Movie.2026.1080p"}
|
||||
assert music_titles == {"Daft Punk - Get Lucky [FLAC]"}
|
||||
assert all(call.kwargs == {"strict": True} for call in save_cache.call_args_list)
|
||||
|
||||
|
||||
def test_rss_refresh_include_music_fetches_dedicated_entry():
|
||||
@@ -315,7 +319,7 @@ def test_rss_refresh_include_music_fetches_dedicated_entry():
|
||||
|
||||
def _fake_browse(domain, keyword=None, cat=None, page=None, mtype=None):
|
||||
"""
|
||||
模拟音乐专用入口的两页抓取结果。
|
||||
模拟音乐专用入口的两页抓取结果,不访问真实站点。
|
||||
"""
|
||||
assert mtype == MediaType.MUSIC
|
||||
return [music_torrent] if not page else []
|
||||
@@ -341,14 +345,15 @@ def test_rss_refresh_include_music_fetches_dedicated_entry():
|
||||
patch.object(
|
||||
chain,
|
||||
"save_cache",
|
||||
side_effect=lambda data, filename: saved.__setitem__(filename, copy.deepcopy(data)),
|
||||
),
|
||||
side_effect=lambda data, filename, **_kwargs: saved.__setitem__(filename, copy.deepcopy(data)),
|
||||
) as save_cache,
|
||||
patch("app.chain.torrents.SitesHelper", return_value=sites_helper),
|
||||
patch("app.chain.torrents.MediaChain"),
|
||||
):
|
||||
result = chain.refresh(stype="rss", sites=[1], include_music=True)
|
||||
|
||||
browse.assert_called()
|
||||
assert all(call.kwargs == {"strict": True} for call in save_cache.call_args_list)
|
||||
assert {
|
||||
context.torrent_info.title for context in result["example.com"]
|
||||
} == {video_torrent.title, music_torrent.title}
|
||||
@@ -365,6 +370,9 @@ def test_music_cache_not_evicted_by_video_torrents():
|
||||
chain = TorrentsChain()
|
||||
|
||||
def _music_context(title, enclosure, pubdate):
|
||||
"""
|
||||
构造已识别音乐缓存,验证影视配额不挤出该类资源。
|
||||
"""
|
||||
torrent = TorrentInfo(
|
||||
site=1, site_name="Test", title=title, enclosure=enclosure,
|
||||
category=MediaType.MUSIC.value, pubdate=pubdate,
|
||||
@@ -390,11 +398,17 @@ def test_music_cache_not_evicted_by_video_torrents():
|
||||
]
|
||||
|
||||
def _fake_load(filename):
|
||||
"""
|
||||
仅返回合成音乐缓存,其余文件视为空。
|
||||
"""
|
||||
if filename == TorrentsChain._music_spider_file:
|
||||
return {"example.com": existing_music}
|
||||
return None
|
||||
|
||||
def _fake_browse(domain, keyword=None, cat=None, page=None, mtype=None):
|
||||
"""
|
||||
提供超过影视缓存上限的单页资源。
|
||||
"""
|
||||
return video_torrents if not page else []
|
||||
|
||||
sites_helper = Mock()
|
||||
@@ -402,7 +416,7 @@ def test_music_cache_not_evicted_by_video_torrents():
|
||||
"id": 1, "name": "Test", "domain": "https://example.com",
|
||||
}]
|
||||
saved = {}
|
||||
save_cache = Mock(side_effect=lambda data, filename: saved.__setitem__(filename, copy.deepcopy(data)))
|
||||
save_cache = Mock(side_effect=lambda data, filename, **_kwargs: saved.__setitem__(filename, copy.deepcopy(data)))
|
||||
fake_settings = Mock()
|
||||
# 公共参数:缓存上限 2,刷新配额 5,音乐与影视各自独立计算
|
||||
fake_settings.CONF = SimpleNamespace(torrents=2, refresh=5)
|
||||
@@ -424,6 +438,7 @@ def test_music_cache_not_evicted_by_video_torrents():
|
||||
|
||||
# 影视缓存独立按配额裁剪,仅保留最新的两条
|
||||
assert len(saved[TorrentsChain._spider_file]["example.com"]) == 2
|
||||
assert all(call.kwargs == {"strict": True} for call in save_cache.call_args_list)
|
||||
# 音乐独立缓存不受影视种子大量涌入影响,既有的两条音乐完整保留
|
||||
music_titles = {
|
||||
context.torrent_info.title
|
||||
|
||||
@@ -125,7 +125,8 @@ def test_scheduler_initializer_retains_bindings_when_async_stop_fails(monkeypatc
|
||||
reset_bindings.assert_not_called()
|
||||
|
||||
|
||||
def test_clear_cache_is_manual_only(monkeypatch):
|
||||
@pytest.mark.parametrize("mode", ["spider", "rss"])
|
||||
def test_clear_cache_is_manual_only(monkeypatch, mode):
|
||||
"""
|
||||
缓存清理任务应仅手动执行,不注册到调度器自动运行。
|
||||
"""
|
||||
@@ -152,7 +153,7 @@ def test_clear_cache_is_manual_only(monkeypatch):
|
||||
"get_scheduler_runtime_config",
|
||||
lambda: SchedulerRuntimeConfig(
|
||||
False, "Asia/Shanghai", 1, False, "", 0, None, False, 24,
|
||||
"rss", 30, False, 0, 0, True, 1, False, None,
|
||||
mode, 30, False, 0, 0, True, 1, False, None,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -182,6 +183,33 @@ def test_clear_cache_is_manual_only(monkeypatch):
|
||||
heartbeat = next(job for job in background_scheduler.jobs if job["id"] == "agent_heartbeat")
|
||||
assert heartbeat["executor"] == "agent"
|
||||
assert scheduler._jobs["agent_heartbeat"]["execution_group"] == "agent"
|
||||
refresh_jobs = [job for job in background_scheduler.jobs if job["id"].startswith("subscribe_refresh")]
|
||||
assert len(refresh_jobs) == 1
|
||||
refresh_job = refresh_jobs[0]
|
||||
assert refresh_job["trigger"] == "interval"
|
||||
if mode == "spider":
|
||||
assert refresh_job["minutes"] == 1
|
||||
assert refresh_job["func"] == scheduler._poll_subscription_refresh
|
||||
assert "kwargs" not in refresh_job
|
||||
else:
|
||||
assert refresh_job["minutes"] == 30
|
||||
assert refresh_job["func"] == scheduler.start
|
||||
assert refresh_job["kwargs"] == {"job_id": "subscribe_refresh"}
|
||||
assert scheduler._jobs["subscribe_refresh"]["timeout_seconds"] is None
|
||||
|
||||
|
||||
def test_auto_refresh_poll_skips_active_owner_and_only_auto_uses_due_plan():
|
||||
"""
|
||||
分钟扫描在空闲时传入到期标识;已有真实任务时不重入,也不改人工任务的参数。
|
||||
"""
|
||||
scheduler = object.__new__(Scheduler)
|
||||
scheduler._is_job_active = Mock(return_value=True)
|
||||
scheduler.start = Mock()
|
||||
scheduler._poll_subscription_refresh()
|
||||
scheduler.start.assert_not_called()
|
||||
scheduler._is_job_active.return_value = False
|
||||
scheduler._poll_subscription_refresh()
|
||||
scheduler.start.assert_called_once_with("subscribe_refresh", scheduled=True)
|
||||
|
||||
|
||||
def test_user_auth_refreshes_plugin_routes_after_runtime_reinitialization(monkeypatch):
|
||||
|
||||
@@ -12,7 +12,10 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.chain.subscribe import refresh as subscription_refresh
|
||||
from app.chain.subscribe.refresh import SubscribeRefreshOwner
|
||||
from app.runtime.loop import main_loop_registry
|
||||
from app.runtime.tasks import TaskRegistry
|
||||
from app.scheduler import bridge as scheduler_bridge
|
||||
from app.scheduler import execution as scheduler_execution
|
||||
from app.scheduler import lifecycle as scheduler_lifecycle
|
||||
@@ -145,6 +148,46 @@ def test_internal_loop_submission_requires_job_owner() -> None:
|
||||
assert parameter.annotation is str
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subscription_refresh_stop_keeps_scheduler_owner_until_real_thread_exits(monkeypatch):
|
||||
"""
|
||||
刷新协程取消后 Scheduler 保留同 ID 所有权,停止必须等待真实同步线程退出。
|
||||
"""
|
||||
started, release = threading.Event(), threading.Event()
|
||||
tasks = TaskRegistry()
|
||||
monkeypatch.setattr(subscription_refresh, "get_task_registry", lambda: tasks)
|
||||
owner = object.__new__(SubscribeRefreshOwner)
|
||||
|
||||
def refresh(**_kwargs):
|
||||
"""
|
||||
模拟仍持有真实执行权的阻塞刷新。
|
||||
"""
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
|
||||
owner.refresh = refresh
|
||||
_patch_progress(monkeypatch)
|
||||
scheduler = _scheduler("subscribe_refresh", owner.async_refresh)
|
||||
assert scheduler.start("subscribe_refresh", scheduled=True) is True
|
||||
stopping = None
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
stopping = asyncio.create_task(scheduler.stop_async())
|
||||
await asyncio.sleep(0)
|
||||
assert not stopping.done()
|
||||
assert scheduler._is_job_active("subscribe_refresh")
|
||||
assert scheduler.start("subscribe_refresh", scheduled=True) is False
|
||||
release.set()
|
||||
await asyncio.wait_for(stopping, 2)
|
||||
assert not scheduler._is_job_active("subscribe_refresh")
|
||||
assert not tasks.records
|
||||
finally:
|
||||
release.set()
|
||||
if stopping is not None:
|
||||
await stopping
|
||||
await tasks.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_stop_async_cancels_and_awaits_scheduler_owned_job(monkeypatch) -> None:
|
||||
"""
|
||||
|
||||
@@ -100,6 +100,21 @@ def test_query_owner_only_returns_sites_for_requested_media_type():
|
||||
assert owner.get_subscribed_sites(MediaType.MUSIC.value) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("states", [("S",), ("N",), ("S", "N")])
|
||||
def test_global_refresh_stops_when_no_subscription_is_eligible(states):
|
||||
"""
|
||||
全局刷新只有暂停或尚未首次搜索的订阅时,不能回退到默认全部站点。
|
||||
"""
|
||||
owner = object.__new__(SubscribeQueryOwner)
|
||||
owner.subscription_repository = SimpleNamespace(list=lambda: [
|
||||
SimpleNamespace(state=state, type=MediaType.TV.value) for state in states
|
||||
])
|
||||
owner.get_states_for_search = lambda _state: "R,P"
|
||||
owner.get_sub_sites = Mock()
|
||||
assert owner.get_subscribed_sites() is None
|
||||
owner.get_sub_sites.assert_not_called()
|
||||
|
||||
|
||||
def test_refresh_check_only_processes_requested_media_type():
|
||||
"""
|
||||
订阅元数据检查只把当前媒体类型交给单订阅检查器。
|
||||
|
||||
@@ -260,6 +260,7 @@ def test_subscribe_chain_package_has_single_responsibility_owners() -> None:
|
||||
"music.py",
|
||||
"notify.py",
|
||||
"policy.py",
|
||||
"poll.py",
|
||||
"query.py",
|
||||
"reconcile.py",
|
||||
"refresh.py",
|
||||
|
||||
361
tests/test_subscription_refresh_poll.py
Normal file
361
tests/test_subscription_refresh_poll.py
Normal file
@@ -0,0 +1,361 @@
|
||||
"""
|
||||
自动刷新以真实线程屏障验证慢站隔离、到期合并和关闭所有权。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.subscription.refresh import RefreshPolicy, RefreshSchedule, RefreshSiteState
|
||||
from app.chain.subscribe import poll as poll_module
|
||||
from app.chain.subscribe import refresh as refresh_module
|
||||
from app.chain.subscribe.poll import SubscriptionRefreshPoll
|
||||
from app.chain.subscribe.refresh import SubscribeRefreshOwner
|
||||
from app.runtime.tasks import TaskRegistry
|
||||
|
||||
NOW = datetime(2026, 11, 14, 4, tzinfo=timezone.utc)
|
||||
SITES = [{"id": site_id, "name": f"站点{site_id}", "domain": f"https://site{site_id}.example/"}
|
||||
for site_id in (1, 2)]
|
||||
|
||||
|
||||
def _owner() -> SimpleNamespace:
|
||||
"""
|
||||
提供已到期的合成站点和独立排程缓存,不连接真实站点、数据库或下载器。
|
||||
"""
|
||||
schedule = RefreshSchedule(RefreshPolicy(), {"version": 1, "seed": "test-instance", "sites": {}})
|
||||
schedule.states = {site_id: RefreshSiteState() for site_id in (1, 2)}
|
||||
storage = {"schedule": schedule.snapshot()}
|
||||
|
||||
def save(snapshot, *_args, **_kwargs):
|
||||
"""
|
||||
保存快照副本,模拟真实缓存序列化后的隔离语义。
|
||||
"""
|
||||
storage["schedule"] = deepcopy(snapshot)
|
||||
|
||||
return SimpleNamespace(get_subscribed_sites=Mock(return_value=[1, 2]),
|
||||
has_music_subscribe=Mock(return_value=False), match=Mock(),
|
||||
load_cache=lambda _name: deepcopy(storage["schedule"]), save_cache=Mock(side_effect=save),
|
||||
storage=storage)
|
||||
|
||||
|
||||
def _result(indexer, *_args):
|
||||
"""
|
||||
返回一次真实已访问且成功空页的合成事实。
|
||||
"""
|
||||
return f"site{indexer['id']}.example", [], {"id": indexer["id"], "status": "success", "attempted": True}
|
||||
|
||||
|
||||
def _isolate(monkeypatch, pool, refresh_site):
|
||||
"""
|
||||
替换站点和共享线程池边界,保留轮询器真实 Future 等待与收尾。
|
||||
"""
|
||||
clock = SimpleNamespace(now=NOW)
|
||||
torrents = SimpleNamespace(refresh_indexers=lambda _sites: SITES, refresh_site=refresh_site,
|
||||
get_torrents=lambda: {"site1.example": [], "site2.example": []})
|
||||
monkeypatch.setattr(poll_module, "TorrentsChain", lambda: torrents)
|
||||
monkeypatch.setattr(poll_module, "ThreadHelper", lambda: pool)
|
||||
monkeypatch.setattr(poll_module, "datetime", SimpleNamespace(now=lambda _tz: clock.now))
|
||||
monkeypatch.setattr(poll_module, "runtime_stop_state", SimpleNamespace(is_system_stopped=False))
|
||||
monkeypatch.setattr(poll_module, "_POLL_SECONDS", 0.01)
|
||||
return clock
|
||||
|
||||
|
||||
def test_healthy_site_matches_and_runs_next_slot_before_slow_site_finishes(monkeypatch):
|
||||
"""
|
||||
一个站点阻塞时,另一个站点可先匹配并继续下一到期时间片;最多同时两个工作。
|
||||
"""
|
||||
slow_started, release_slow, twice_matched = threading.Event(), threading.Event(), threading.Event()
|
||||
first_saved = threading.Event()
|
||||
owner = _owner()
|
||||
save = owner.save_cache.side_effect
|
||||
|
||||
def saved(snapshot, *args, **kwargs):
|
||||
"""
|
||||
首次匹配及其合并窗口保存后通知主测试线程,避免在匹配中途推进虚拟时间。
|
||||
"""
|
||||
save(snapshot, *args, **kwargs)
|
||||
if snapshot["match_after"] > NOW.timestamp() and not snapshot["needs_match"]:
|
||||
first_saved.set()
|
||||
|
||||
owner.save_cache.side_effect = saved
|
||||
active = set()
|
||||
guard = threading.Lock()
|
||||
counts = {1: 0, 2: 0}
|
||||
|
||||
def fetch(indexer, *args):
|
||||
"""
|
||||
首站由屏障阻塞,记录真实在途站点以检查同站互斥和并发上限。
|
||||
"""
|
||||
site_id = indexer["id"]
|
||||
with guard:
|
||||
assert site_id not in active
|
||||
active.add(site_id)
|
||||
counts[site_id] += 1
|
||||
assert len(active) <= 2
|
||||
try:
|
||||
if site_id == 1:
|
||||
slow_started.set()
|
||||
assert release_slow.wait(5)
|
||||
return _result(indexer, *args)
|
||||
finally:
|
||||
with guard:
|
||||
active.remove(site_id)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as workers, ThreadPoolExecutor(max_workers=1) as caller:
|
||||
clock = _isolate(monkeypatch, workers, fetch)
|
||||
|
||||
def matched(*_args, **_kwargs):
|
||||
"""
|
||||
第二次健康结果匹配后结束本轮新提交。
|
||||
"""
|
||||
if owner.match.call_count == 2:
|
||||
owner.get_subscribed_sites.return_value = None
|
||||
twice_matched.set()
|
||||
|
||||
owner.match.side_effect = matched
|
||||
poll = SubscriptionRefreshPoll(owner, RefreshPolicy())
|
||||
future = caller.submit(poll.run)
|
||||
try:
|
||||
assert slow_started.wait(2)
|
||||
assert first_saved.wait(2)
|
||||
clock.now += timedelta(hours=3)
|
||||
assert twice_matched.wait(2)
|
||||
assert counts[2] == 2
|
||||
assert counts[1] == 1
|
||||
assert not future.done()
|
||||
assert len(poll.pending) == 1
|
||||
finally:
|
||||
release_slow.set()
|
||||
future.result(timeout=2)
|
||||
assert not active
|
||||
assert not poll.pending
|
||||
|
||||
|
||||
def test_single_site_failure_does_not_abort_healthy_work(monkeypatch):
|
||||
"""
|
||||
单站抛错会记录该站冷却,其他站仍完成匹配,保存的事实不包含错误中的凭据。
|
||||
"""
|
||||
owner = _owner()
|
||||
|
||||
def fetch(indexer, *args):
|
||||
"""
|
||||
用含合成敏感文本的异常检查排程快照不会存入原始错误。
|
||||
"""
|
||||
if indexer["id"] == 1:
|
||||
raise RuntimeError("synthetic-secret-value")
|
||||
return _result(indexer, *args)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as workers:
|
||||
_isolate(monkeypatch, workers, fetch)
|
||||
poll = SubscriptionRefreshPoll(owner, RefreshPolicy())
|
||||
poll.run()
|
||||
assert owner.match.called
|
||||
snapshot = owner.storage["schedule"]
|
||||
assert snapshot["sites"]["1"]["failures"] == 1
|
||||
assert snapshot["sites"]["2"]["last_success"] == NOW.timestamp()
|
||||
assert "synthetic-secret-value" not in str(snapshot)
|
||||
assert not poll.pending
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop_kind", ["runtime", "cancellation"])
|
||||
def test_stop_drains_real_workers_before_returning(monkeypatch, stop_kind):
|
||||
"""
|
||||
停止信号后不再匹配或提交,调用方等待同步 worker 真正结束才返回。
|
||||
"""
|
||||
started, release = threading.Event(), threading.Event()
|
||||
cancelled = threading.Event()
|
||||
owner = _owner()
|
||||
|
||||
def fetch(indexer, *args):
|
||||
"""
|
||||
在真实 Future 内等待释放,模拟不可强制取消的同步请求。
|
||||
"""
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return _result(indexer, *args)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as workers, ThreadPoolExecutor(max_workers=1) as caller:
|
||||
_isolate(monkeypatch, workers, fetch)
|
||||
stop = SimpleNamespace(is_system_stopped=False)
|
||||
monkeypatch.setattr(poll_module, "runtime_stop_state", stop)
|
||||
poll = SubscriptionRefreshPoll(owner, RefreshPolicy(), stop_event=cancelled)
|
||||
future = caller.submit(poll.run)
|
||||
try:
|
||||
assert started.wait(2)
|
||||
if stop_kind == "runtime":
|
||||
stop.is_system_stopped = True
|
||||
else:
|
||||
cancelled.set()
|
||||
assert not future.done()
|
||||
finally:
|
||||
release.set()
|
||||
future.result(timeout=2)
|
||||
owner.match.assert_not_called()
|
||||
assert not poll.pending
|
||||
|
||||
|
||||
def test_empty_scan_never_submits_or_matches(monkeypatch):
|
||||
"""
|
||||
到期前扫描只检查排程,不能把每分钟轮询变成每分钟访问站点。
|
||||
"""
|
||||
owner = _owner()
|
||||
for state in owner.storage["schedule"]["sites"].values():
|
||||
state["next_due"] = NOW.timestamp() + 3600
|
||||
with ThreadPoolExecutor(max_workers=2) as workers:
|
||||
fetch = Mock(side_effect=_result)
|
||||
_isolate(monkeypatch, workers, fetch)
|
||||
SubscriptionRefreshPoll(owner, RefreshPolicy()).run()
|
||||
fetch.assert_not_called()
|
||||
owner.match.assert_not_called()
|
||||
owner.save_cache.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scheduled,mode,uses_plan", [(True, "spider", True), (False, "spider", False),
|
||||
(True, "rss", False), (False, "rss", False)])
|
||||
def test_only_scheduled_spider_uses_due_plan(monkeypatch, scheduled, mode, uses_plan):
|
||||
"""
|
||||
自动 spider 使用到期计划,手工刷新和 RSS 仍直接刷新所选站点并匹配。
|
||||
"""
|
||||
owner = object.__new__(SubscribeRefreshOwner)
|
||||
owner.runtime_config = SimpleNamespace(subscribe_mode=mode)
|
||||
owner.get_subscribed_sites = Mock(return_value=[1])
|
||||
owner.has_music_subscribe = Mock(return_value=False)
|
||||
owner.match = Mock()
|
||||
poll, torrents = Mock(), Mock()
|
||||
monkeypatch.setattr(refresh_module, "SubscriptionRefreshPoll", poll)
|
||||
monkeypatch.setattr(refresh_module, "TorrentsChain", lambda: torrents)
|
||||
monkeypatch.setattr(refresh_module, "get_scheduler_runtime_config", lambda: SimpleNamespace(timezone="Asia/Shanghai"))
|
||||
owner.refresh(scheduled=scheduled)
|
||||
assert poll.return_value.run.called is uses_plan
|
||||
assert torrents.refresh.called is not uses_plan
|
||||
assert owner.match.called is not uses_plan
|
||||
|
||||
|
||||
def test_failed_match_is_recovered_from_cache_without_refetching(monkeypatch):
|
||||
"""
|
||||
抓取完成后匹配抛错,重建轮询器仍从缓存完成匹配,不额外消耗站点请求。
|
||||
"""
|
||||
owner = _owner()
|
||||
owner.match.side_effect = RuntimeError("synthetic matching failure")
|
||||
fetch = Mock(side_effect=_result)
|
||||
with ThreadPoolExecutor(max_workers=2) as workers:
|
||||
_isolate(monkeypatch, workers, fetch)
|
||||
with pytest.raises(RuntimeError, match="synthetic matching failure"):
|
||||
SubscriptionRefreshPoll(owner, RefreshPolicy()).run()
|
||||
assert owner.storage["schedule"]["needs_match"] is True
|
||||
assert fetch.call_count == 2
|
||||
owner.match.side_effect = None
|
||||
SubscriptionRefreshPoll(owner, RefreshPolicy()).run()
|
||||
assert fetch.call_count == 2
|
||||
assert owner.storage["schedule"]["needs_match"] is False
|
||||
|
||||
|
||||
def test_matching_window_coalesces_site_results_and_survives_restart(monkeypatch):
|
||||
"""
|
||||
五分钟内完成的其他站点集中匹配,跨轮次恢复安全计数且不重复抓取资源。
|
||||
"""
|
||||
release_second = threading.Event()
|
||||
owner = _owner()
|
||||
|
||||
def fetch(indexer, *args):
|
||||
"""
|
||||
等待首站完成匹配后才返回第二站,制造同一合并窗口的后续结果。
|
||||
"""
|
||||
if indexer["id"] == 2:
|
||||
assert release_second.wait(5)
|
||||
return _result(indexer, *args)
|
||||
|
||||
owner.match.side_effect = lambda *_args, **_kwargs: release_second.set()
|
||||
with ThreadPoolExecutor(max_workers=2) as workers:
|
||||
request = Mock(side_effect=fetch)
|
||||
clock = _isolate(monkeypatch, workers, request)
|
||||
SubscriptionRefreshPoll(owner, RefreshPolicy()).run()
|
||||
assert owner.match.call_count == 1
|
||||
snapshot = owner.storage["schedule"]
|
||||
assert snapshot["needs_match"] is True
|
||||
assert [fact["id"] for fact in snapshot["pending_facts"]] == [2]
|
||||
assert "name" not in snapshot["pending_facts"][0]
|
||||
clock.now += timedelta(minutes=2)
|
||||
SubscriptionRefreshPoll(owner, RefreshPolicy()).run()
|
||||
assert owner.match.call_count == 1
|
||||
clock.now += timedelta(minutes=3)
|
||||
SubscriptionRefreshPoll(owner, RefreshPolicy()).run()
|
||||
assert request.call_count == 2
|
||||
assert owner.match.call_count == 2
|
||||
assert owner.match.call_args.kwargs["site_facts"] == ({"id": 2, "status": "success", "attempted": True, "name": "站点2"},)
|
||||
assert owner.storage["schedule"]["needs_match"] is False
|
||||
assert "pending_facts" not in owner.storage["schedule"]
|
||||
|
||||
|
||||
def test_failed_schedule_save_still_waits_for_accepted_real_work(monkeypatch):
|
||||
"""
|
||||
排程保存失败也必须等待已接受的同步抓取退出,不能泄漏站点执行所有权。
|
||||
"""
|
||||
started, release = threading.Event(), threading.Event()
|
||||
owner = _owner()
|
||||
owner.save_cache.side_effect = OSError("synthetic disk failure")
|
||||
# 使派发前的排程状态发生变化,触发确认保存路径。
|
||||
owner.storage["schedule"]["sites"]["3"] = {}
|
||||
|
||||
def fetch(indexer, *args):
|
||||
"""
|
||||
将已接受请求保持在真实线程内,供保存失败后的收尾检查。
|
||||
"""
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return _result(indexer, *args)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as workers, ThreadPoolExecutor(max_workers=1) as caller:
|
||||
_isolate(monkeypatch, workers, fetch)
|
||||
poll = SubscriptionRefreshPoll(owner, RefreshPolicy())
|
||||
future = caller.submit(poll.run)
|
||||
try:
|
||||
assert started.wait(2)
|
||||
assert not future.done()
|
||||
finally:
|
||||
release.set()
|
||||
with pytest.raises(OSError, match="synthetic disk failure"):
|
||||
future.result(timeout=2)
|
||||
assert not poll.pending
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_refresh_cancellation_retains_real_work_owner(monkeypatch):
|
||||
"""
|
||||
取消异步外壳后仍保留线程工作,真实结束后才向 Scheduler 传播取消。
|
||||
"""
|
||||
started, release, sealed = threading.Event(), threading.Event(), threading.Event()
|
||||
registry = TaskRegistry()
|
||||
monkeypatch.setattr(refresh_module, "get_task_registry", lambda: registry)
|
||||
owner = object.__new__(SubscribeRefreshOwner)
|
||||
|
||||
def refresh(**kwargs):
|
||||
"""
|
||||
模拟仍在执行的同步刷新入口。
|
||||
"""
|
||||
started.set()
|
||||
assert kwargs["_stop_event"].wait(2)
|
||||
sealed.set()
|
||||
assert release.wait(5)
|
||||
|
||||
owner.refresh = refresh
|
||||
task = asyncio.create_task(owner.async_refresh(scheduled=True))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
task.cancel()
|
||||
assert await asyncio.to_thread(sealed.wait, 2)
|
||||
assert not task.done()
|
||||
assert registry.records
|
||||
release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, timeout=2)
|
||||
assert not registry.records
|
||||
finally:
|
||||
release.set()
|
||||
await registry.shutdown()
|
||||
193
tests/test_subscription_refresh_schedule.py
Normal file
193
tests/test_subscription_refresh_schedule.py
Normal file
@@ -0,0 +1,193 @@
|
||||
"""
|
||||
自动订阅刷新在虚拟时间下的预算、覆盖、冷却和重启恢复合同。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.subscription.refresh import RefreshPolicy, RefreshSchedule, RefreshSiteState
|
||||
|
||||
NOW = datetime(2026, 11, 14, 4, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def _schedule(policy: RefreshPolicy = RefreshPolicy()) -> RefreshSchedule:
|
||||
"""
|
||||
使用固定实例盐,保留真实的跨日和跨站时间片算法。
|
||||
"""
|
||||
return RefreshSchedule(policy, {"version": 1, "seed": "synthetic-instance", "sites": {}})
|
||||
|
||||
|
||||
def test_daily_slots_cover_day_and_night_with_bounded_gaps() -> None:
|
||||
"""
|
||||
每天固定预算覆盖完整时段,连续多日的最长间隔受时间片抖动限制。
|
||||
"""
|
||||
policy = RefreshPolicy()
|
||||
anchor = NOW.astimezone(ZoneInfo(policy.timezone_name))
|
||||
slots = [slot for day in range(20) for slot in policy.slots(anchor + timedelta(days=day), "instance", 1)]
|
||||
assert len(slots) == 20 * 36
|
||||
assert len(set(slots)) == len(slots)
|
||||
for day in range(20):
|
||||
daily = slots[day * 36:(day + 1) * 36]
|
||||
daytime = [slot for slot in daily if 7 <= slot.hour < 23]
|
||||
assert len(daytime) == 32
|
||||
assert sum(slot.hour < 7 or slot.hour >= 23 for slot in daily) == 4
|
||||
assert all((right - left).total_seconds() < 42 * 60 for left, right in zip(daytime, daytime[1:]))
|
||||
gaps = [(right - left).total_seconds() for left, right in zip(slots, slots[1:])]
|
||||
assert max(gaps) < 168 * 60
|
||||
assert min(gaps) > 18 * 60
|
||||
|
||||
|
||||
@pytest.mark.parametrize("timezone_name", ["Asia/Shanghai", "America/New_York", "Europe/Berlin"])
|
||||
def test_timezones_and_dst_keep_unique_ordered_real_instants(timezone_name: str) -> None:
|
||||
"""
|
||||
夏令时切换周仍保持预算,所有触发时刻在真实时间上严格递增。
|
||||
"""
|
||||
policy = RefreshPolicy(timezone_name=timezone_name)
|
||||
for month, day in ((3, 7), (10, 31)):
|
||||
anchor = datetime(2026, month, day, tzinfo=ZoneInfo(timezone_name))
|
||||
slots = [slot.timestamp() for offset in range(3)
|
||||
for slot in policy.slots(anchor + timedelta(days=offset), "instance", 1)]
|
||||
assert len(slots) == 108
|
||||
assert all(right > left for left, right in zip(slots, slots[1:]))
|
||||
|
||||
|
||||
def test_instances_sites_and_days_have_distinct_stable_phases() -> None:
|
||||
"""
|
||||
同一实例重算不改变时间,站点、实例及日期之间均分散请求。
|
||||
"""
|
||||
policy = RefreshPolicy()
|
||||
assert policy.slots(NOW, "a", 1) == policy.slots(NOW, "a", 1)
|
||||
assert policy.slots(NOW, "a", 1) != policy.slots(NOW, "b", 1)
|
||||
assert policy.slots(NOW, "a", 1) != policy.slots(NOW, "a", 2)
|
||||
first = policy.slots(NOW, "a", 1)
|
||||
following = policy.slots(NOW + timedelta(days=1), "a", 1)
|
||||
assert [item.minute for item in first] != [item.minute for item in following]
|
||||
|
||||
|
||||
def test_cold_start_spreads_sites_then_consumes_at_most_one_current_slot() -> None:
|
||||
"""
|
||||
新站首轮五分钟内分散;同一时间片的重复扫描不重复访问。
|
||||
"""
|
||||
schedule = _schedule()
|
||||
site_ids = list(range(1, 51))
|
||||
schedule.due(site_ids, NOW)
|
||||
assert all(NOW.timestamp() <= state.next_due < NOW.timestamp() + 300 for state in schedule.states.values())
|
||||
assert len({state.next_due for state in schedule.states.values()}) > 30
|
||||
now = NOW + timedelta(minutes=6)
|
||||
assert set(schedule.due(site_ids, now)) == set(site_ids)
|
||||
for site_id in site_ids:
|
||||
schedule.finish(site_id, now, {"status": "success", "attempted": True}, now)
|
||||
assert schedule.due(site_ids, now) == []
|
||||
restored = RefreshSchedule(schedule.policy, schedule.snapshot())
|
||||
assert restored.due(site_ids, now) == []
|
||||
assert restored.seed == schedule.seed
|
||||
|
||||
|
||||
def test_long_outage_coalesces_to_one_current_opportunity() -> None:
|
||||
"""
|
||||
停机多日不回放历史时间片,本次完成后只等待下一次计划。
|
||||
"""
|
||||
schedule = _schedule()
|
||||
schedule.states[1] = RefreshSiteState(slot=NOW.timestamp() - 86400 * 20)
|
||||
assert schedule.due([1], NOW) == [1]
|
||||
schedule.finish(1, NOW, {"status": "success"}, NOW)
|
||||
assert schedule.due([1], NOW + timedelta(seconds=1)) == []
|
||||
|
||||
|
||||
def test_missed_slots_during_work_produce_only_one_new_due() -> None:
|
||||
"""
|
||||
长工作跨越多个时间片后只合并一次新机会,不按漏掉次数积压请求。
|
||||
"""
|
||||
schedule = _schedule()
|
||||
schedule.states[1] = RefreshSiteState()
|
||||
finished = NOW + timedelta(hours=4)
|
||||
schedule.finish(1, NOW, {"status": "success"}, finished)
|
||||
assert schedule.due([1], finished) == [1]
|
||||
schedule.finish(1, finished, {"status": "success"}, finished)
|
||||
assert schedule.due([1], finished) == []
|
||||
|
||||
|
||||
def test_deferred_work_preserves_budget_and_honors_cooldown() -> None:
|
||||
"""
|
||||
未发请求的限流不消费时间片,冷却到期可继续一次。
|
||||
"""
|
||||
schedule = _schedule()
|
||||
schedule.states[1] = RefreshSiteState()
|
||||
schedule.finish(1, NOW, {"status": "deferred", "attempted": False, "retry_after": 600}, NOW)
|
||||
assert schedule.states[1].slot == 0
|
||||
assert schedule.states[1].failures == 0
|
||||
assert schedule.due([1], NOW + timedelta(seconds=599)) == []
|
||||
assert schedule.due([1], NOW + timedelta(seconds=600)) == [1]
|
||||
|
||||
|
||||
def test_failures_back_off_per_site_and_successful_empty_page_recovers() -> None:
|
||||
"""
|
||||
单站失败冷却持久化且不影响其他站;成功空页不能被当成失败。
|
||||
"""
|
||||
schedule = _schedule()
|
||||
schedule.states = {1: RefreshSiteState(failures=4), 2: RefreshSiteState()}
|
||||
schedule.finish(1, NOW, {"status": "failed"}, NOW)
|
||||
assert schedule.states[1].failures == 5
|
||||
assert schedule.states[1].next_due >= NOW.timestamp() + 7200
|
||||
assert schedule.due([1, 2], NOW) == [2]
|
||||
restored = RefreshSchedule(schedule.policy, schedule.snapshot())
|
||||
assert restored.due([1, 2], NOW) == [2]
|
||||
later = NOW + timedelta(hours=3)
|
||||
restored.finish(1, later, {"status": "success", "candidates": 0}, later)
|
||||
assert restored.states[1].failures == 0
|
||||
assert restored.states[1].last_success == later.timestamp()
|
||||
|
||||
|
||||
def test_partial_request_deferred_keeps_minimum_gap_between_dense_day_slots() -> None:
|
||||
"""
|
||||
白天加密后,首页已访问但后页限流仍保留 20 分钟间隔,不能在相邻短时间片追加访问。
|
||||
"""
|
||||
schedule = _schedule()
|
||||
anchor = NOW.astimezone(ZoneInfo(schedule.policy.timezone_name))
|
||||
slots = [slot for day in range(20)
|
||||
for slot in schedule.policy.slots(anchor + timedelta(days=day), schedule.seed, 1)]
|
||||
started, following = next((left, right) for left, right in zip(slots, slots[1:])
|
||||
if (right - left).total_seconds() < 20 * 60)
|
||||
schedule.states[1] = RefreshSiteState()
|
||||
schedule.finish(1, started, {"status": "deferred", "attempted": True, "retry_after": 60}, started)
|
||||
restored = RefreshSchedule(schedule.policy, schedule.snapshot())
|
||||
assert restored.due([1], following) == []
|
||||
assert restored.due([1], started + timedelta(minutes=20)) == [1]
|
||||
|
||||
|
||||
def test_removed_sites_are_pruned_without_exposing_resource_or_credentials() -> None:
|
||||
"""
|
||||
排程只保存当前站点的时间事实,移除站点后回收对应记录。
|
||||
"""
|
||||
schedule = _schedule()
|
||||
schedule.states = {1: RefreshSiteState(), 2: RefreshSiteState()}
|
||||
schedule.due([2], NOW)
|
||||
assert set(schedule.snapshot()["sites"]) == {"2"}
|
||||
assert schedule.next_due() is not None
|
||||
|
||||
|
||||
def test_remote_cooldown_longer_than_local_backoff_is_preserved() -> None:
|
||||
"""
|
||||
实际请求遇到长 Retry-After 时不被本地退避上限缩短,重启后也保留该时间。
|
||||
"""
|
||||
schedule = _schedule()
|
||||
schedule.states[1] = RefreshSiteState()
|
||||
schedule.finish(1, NOW, {"status": "rate_limited", "attempted": True, "retry_after": 43200}, NOW)
|
||||
restored = RefreshSchedule(schedule.policy, schedule.snapshot())
|
||||
assert restored.due([1], NOW + timedelta(hours=11)) == []
|
||||
assert restored.due([1], NOW + timedelta(hours=12)) == [1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("snapshot", [None, [], {"version": 0}, {
|
||||
"version": 1, "seed": "synthetic", "sites": {"1": {"next_due": float("nan")}, "bad": {}, "2": {"bad": 1}},
|
||||
}])
|
||||
def test_invalid_cache_reconstructs_schedule(snapshot) -> None:
|
||||
"""
|
||||
损坏的内部排程重建有效站点状态,不沿用非有限时间或未知字段。
|
||||
"""
|
||||
schedule = RefreshSchedule(RefreshPolicy(), snapshot)
|
||||
assert schedule.states == {}
|
||||
schedule.due([1], NOW)
|
||||
assert 1 in schedule.states
|
||||
218
tests/test_torrents_refresh_concurrency.py
Normal file
218
tests/test_torrents_refresh_concurrency.py
Normal file
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
逐站刷新以真实缓存序列化和线程屏障验证短锁、合并及识别修正保护。
|
||||
"""
|
||||
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.configuration import ChainRuntimeConfig
|
||||
from app.application.site.observation import report_site_search_outcome
|
||||
from app.chain import torrents as torrents_module
|
||||
from app.chain.base import ChainBase
|
||||
from app.chain.torrents import TorrentsChain
|
||||
from app.domain.context import Context, MediaInfo, TorrentInfo
|
||||
from app.runtime.cache import cache_mutation
|
||||
from app.schemas.types import MediaType
|
||||
|
||||
|
||||
def _site(site_id: int) -> dict:
|
||||
"""
|
||||
构造两个完全隔离的合成站点。
|
||||
"""
|
||||
return {"id": site_id, "name": f"站点{site_id}", "domain": f"https://site{site_id}.example/"}
|
||||
|
||||
|
||||
def _torrent(site_id: int, torrent_id: int = 1) -> TorrentInfo:
|
||||
"""
|
||||
使用稳定详情页 ID,保留影视分类及可轮换的下载地址。
|
||||
"""
|
||||
return TorrentInfo(site=site_id, title=f"Series {site_id} S01E{torrent_id:02d}",
|
||||
category=MediaType.TV.value, enclosure=f"https://site{site_id}.example/download.php?id={torrent_id}",
|
||||
page_url=f"https://site{site_id}.example/details.php?id={torrent_id}")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def chain(monkeypatch):
|
||||
"""
|
||||
仅替换缓存和外部识别边界,保留真实同步序列化和所有刷新逻辑。
|
||||
"""
|
||||
storage = {}
|
||||
owner = object.__new__(TorrentsChain)
|
||||
owner.filecache = SimpleNamespace(get=lambda key: storage.get(key), set=lambda key, value: storage.__setitem__(key, value))
|
||||
owner.runtime_config = ChainRuntimeConfig(media_extensions=())
|
||||
owner._build_refresh_context = Mock(side_effect=lambda torrent, _stype: Context(torrent_info=torrent))
|
||||
monkeypatch.setattr(TorrentsChain, "_refresh_sites_lock", threading.Lock())
|
||||
monkeypatch.setattr(TorrentsChain, "_refreshing_sites", set())
|
||||
monkeypatch.setattr(torrents_module.TorrentHelper, "is_invalid", lambda _self, _url: False)
|
||||
monkeypatch.setattr(torrents_module, "site_request_cooldown", lambda _site: 0)
|
||||
return owner
|
||||
|
||||
|
||||
def test_parallel_sites_preserve_both_caches_and_do_not_hold_lock_during_recognition(chain):
|
||||
"""
|
||||
首站识别阻塞期间第二站仍能保存;首站随后合并不会覆盖第二站的数据。
|
||||
"""
|
||||
started, release = threading.Event(), threading.Event()
|
||||
|
||||
def identify(torrent, _stype):
|
||||
"""
|
||||
仅阻塞首站的识别阶段。
|
||||
"""
|
||||
if torrent.site == 1:
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return Context(torrent_info=torrent)
|
||||
|
||||
chain._build_refresh_context.side_effect = identify
|
||||
chain.browse = lambda domain, page: [] if page else [_torrent(1 if domain == "site1.example" else 2)]
|
||||
with ThreadPoolExecutor(max_workers=2) as workers:
|
||||
first = workers.submit(chain.refresh_site, _site(1))
|
||||
try:
|
||||
assert started.wait(2)
|
||||
second = workers.submit(chain.refresh_site, _site(2))
|
||||
assert second.result(timeout=2)[0] == "site2.example"
|
||||
assert not first.done()
|
||||
assert chain.load_cache(chain.cache_file)["site2.example"]
|
||||
finally:
|
||||
release.set()
|
||||
first.result(timeout=2)
|
||||
assert set(chain.load_cache(chain.cache_file)) == {"site1.example", "site2.example"}
|
||||
assert not chain._refreshing_sites
|
||||
|
||||
|
||||
def test_same_site_is_not_reentered_and_busy_call_returns_current_candidates(chain):
|
||||
"""
|
||||
同站在途时不能再发请求,兼容调用仍能读取该站已经存在的候选。
|
||||
"""
|
||||
started, release = threading.Event(), threading.Event()
|
||||
chain.save_cache({"site1.example": [Context(torrent_info=_torrent(1, 1))]}, chain.cache_file)
|
||||
|
||||
def identify(torrent, _stype):
|
||||
"""
|
||||
保留已取得的站点执行权直至释放屏障。
|
||||
"""
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return Context(torrent_info=torrent)
|
||||
|
||||
chain._build_refresh_context.side_effect = identify
|
||||
chain.browse = Mock(side_effect=lambda **kwargs: [] if kwargs["page"] else [_torrent(1, 2)])
|
||||
with ThreadPoolExecutor(max_workers=1) as workers:
|
||||
first = workers.submit(chain.refresh_site, _site(1))
|
||||
try:
|
||||
assert started.wait(2)
|
||||
calls = chain.browse.call_count
|
||||
_, candidates, fact = chain.refresh_site(_site(1))
|
||||
assert chain.browse.call_count == calls
|
||||
assert len(candidates) == 1
|
||||
assert fact["status"] == "deferred"
|
||||
assert fact["attempted"] is False
|
||||
finally:
|
||||
release.set()
|
||||
first.result(timeout=2)
|
||||
|
||||
|
||||
def test_optimistic_merge_preserves_manual_recognition_written_during_fetch(chain):
|
||||
"""
|
||||
识别新资源期间人工修正旧资源,最终合并保留人工身份及最新下载元数据。
|
||||
"""
|
||||
started, release = threading.Event(), threading.Event()
|
||||
old = Context(torrent_info=_torrent(1, 1), media_info=MediaInfo(title="原识别"))
|
||||
chain.save_cache({"site1.example": [old]}, chain.cache_file)
|
||||
latest = _torrent(1, 1)
|
||||
latest.seeders = 10
|
||||
chain.browse = lambda domain, page: [] if page else [latest, _torrent(1, 2)]
|
||||
|
||||
def identify(torrent, _stype):
|
||||
"""
|
||||
在缓存读取后阻塞新资源识别,为人工修正制造确定窗口。
|
||||
"""
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return Context(torrent_info=torrent)
|
||||
|
||||
chain._build_refresh_context.side_effect = identify
|
||||
with ThreadPoolExecutor(max_workers=1) as workers:
|
||||
future = workers.submit(chain.refresh_site, _site(1))
|
||||
try:
|
||||
assert started.wait(2)
|
||||
with cache_mutation("torrent-snapshots"):
|
||||
corrected = chain.load_cache(chain.cache_file)
|
||||
corrected["site1.example"][0].media_info = MediaInfo(title="人工修正")
|
||||
chain.save_cache(corrected, chain.cache_file)
|
||||
finally:
|
||||
release.set()
|
||||
future.result(timeout=2)
|
||||
cache = chain.load_cache(chain.cache_file)["site1.example"]
|
||||
assert len(cache) == 2
|
||||
assert cache[0].media_info.title == "人工修正"
|
||||
assert cache[0].torrent_info.seeders == 10
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attempted,outcome", [(True, "success"), (True, "failed"), (False, "deferred")])
|
||||
def test_empty_page_retains_request_outcome_instead_of_inferring_success(chain, monkeypatch, attempted, outcome):
|
||||
"""
|
||||
成功空页、失败和限流虽同样返回空列表,排程仍能得到不同的执行事实。
|
||||
"""
|
||||
def browse(**_kwargs):
|
||||
"""
|
||||
在真实观察上下文内发布索引器事实。
|
||||
"""
|
||||
report_site_search_outcome(attempted=attempted, outcome=outcome)
|
||||
return []
|
||||
|
||||
chain.browse = browse
|
||||
monkeypatch.setattr(torrents_module, "site_request_cooldown", lambda _site: 600)
|
||||
_, _, fact = chain.refresh_site(_site(1))
|
||||
assert fact["attempted"] is attempted
|
||||
assert fact["status"] == outcome
|
||||
assert fact["retry_after"] == 600
|
||||
|
||||
|
||||
def test_failed_cache_write_is_reported_and_site_owner_is_released(chain):
|
||||
"""
|
||||
缓存保存失败必须传播,同时释放真实已结束的站点 owner。
|
||||
"""
|
||||
chain.browse = lambda **_kwargs: []
|
||||
chain.filecache.set = Mock(side_effect=OSError("synthetic disk failure"))
|
||||
with pytest.raises(OSError, match="synthetic disk failure"):
|
||||
chain.refresh_site(_site(1))
|
||||
assert not chain._refreshing_sites
|
||||
|
||||
|
||||
def test_music_later_page_deferred_preserves_earlier_request_fact(chain):
|
||||
"""
|
||||
音乐首页成功、后页限流时仍记录已请求,不能把整站误判为未访问而追加预算。
|
||||
"""
|
||||
def browse(*, mtype=None, page=0, **_kwargs):
|
||||
"""
|
||||
普通页成功为空,音乐首页有资源,音乐后页发布未请求的限流事实。
|
||||
"""
|
||||
deferred = mtype is not None and page == 1
|
||||
report_site_search_outcome(attempted=not deferred, outcome="deferred" if deferred else "success")
|
||||
if mtype is not None and page == 0:
|
||||
torrent = _torrent(1)
|
||||
torrent.category = MediaType.MUSIC.value
|
||||
return [torrent]
|
||||
return []
|
||||
|
||||
chain.browse = browse
|
||||
indexer = {**_site(1), "search": {"paths": [{"path": "/all"}, {"type": "music", "path": "/music"}]}}
|
||||
_, contexts, fact = chain.refresh_site(indexer, include_music=True)
|
||||
assert len(contexts) == 1
|
||||
assert fact["attempted"] is True
|
||||
assert fact["status"] == "deferred"
|
||||
|
||||
|
||||
def test_sync_cache_strict_mode_preserves_legacy_nonthrowing_default(chain):
|
||||
"""
|
||||
确认保存的宿主路径传播失败,原插件调用仍保留记录日志后返回的默认行为。
|
||||
"""
|
||||
chain.filecache.set = Mock(side_effect=OSError("synthetic disk failure"))
|
||||
ChainBase.save_cache(chain, {}, "synthetic-cache")
|
||||
with pytest.raises(OSError):
|
||||
ChainBase.save_cache(chain, {}, "synthetic-cache", strict=True)
|
||||
Reference in New Issue
Block a user