mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-28 23:16:35 +08:00
fix: 限制插件生命周期准入并保留慢钩子所有权 (#7268)
This commit is contained in:
@@ -269,8 +269,9 @@ async def runtime_status(
|
||||
_SchemaPluginRuntimeStatus.LOAD_FAILED,
|
||||
_SchemaPluginRuntimeStatus.INCOMPATIBLE_RUNTIME,
|
||||
}
|
||||
activity = plugin_manager.get_plugin_lifecycle_activity()
|
||||
return _SchemaPluginRuntimeSummary(
|
||||
ready=not plugin_manager.is_plugin_settling(),
|
||||
ready=not plugin_manager.is_plugin_settling() and activity is None,
|
||||
generation=plugin_manager.get_plugin_runtime_generation(),
|
||||
pending_count=sum(status in pending for status in statuses.values()),
|
||||
failed_count=sum(status in failed for status in statuses.values()),
|
||||
@@ -280,6 +281,7 @@ async def runtime_status(
|
||||
for plugin_id in plugin_manager.get_plugin_gil_fallbacks()
|
||||
if plugin_id.lower() in installed_plugin_ids
|
||||
],
|
||||
active_operation=activity,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ from app.application.plugin.source import (
|
||||
select_plugin_candidate,
|
||||
)
|
||||
from app.domain.plugin import PLUGIN_SYSTEM_VERSION_FIELD
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
|
||||
InventoryProvider = Callable[[bool], Awaitable[CandidateInventory]]
|
||||
IdentityReader = Callable[[str], Awaitable[PluginIdentity | None]]
|
||||
@@ -168,6 +169,8 @@ class PluginInstallGateway:
|
||||
PluginLocalCandidate,
|
||||
),
|
||||
)
|
||||
except PluginMutationRejectedError as error:
|
||||
return PluginInstallResult(success=False, message=str(error), failure_stage="admission")
|
||||
except (TypeError, ValueError, PluginSourceAdmissionError) as error:
|
||||
return PluginInstallResult(
|
||||
success=False,
|
||||
|
||||
@@ -6,9 +6,12 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
|
||||
|
||||
class PluginStartupLease:
|
||||
"""
|
||||
@@ -24,13 +27,21 @@ class PluginLifecycleCoordinator:
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
初始化逐插件资格、启动令牌与持有时刻。
|
||||
"""
|
||||
self._condition = threading.Condition()
|
||||
self._active_plugins: set[str] = set()
|
||||
self._started_at: dict[str, float] = {}
|
||||
self._startup_active = False
|
||||
self._startup_started_at = 0.0
|
||||
self._startup_token: PluginStartupLease | None = None
|
||||
|
||||
@staticmethod
|
||||
def _normalize(plugin_id: str) -> str:
|
||||
"""
|
||||
按源码身份归一插件标识,避免大小写绕过互斥。
|
||||
"""
|
||||
return (plugin_id or "").strip().lower()
|
||||
|
||||
def _try_acquire_plugin(
|
||||
@@ -38,6 +49,9 @@ class PluginLifecycleCoordinator:
|
||||
plugin_id: str,
|
||||
startup_token: PluginStartupLease | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
原子尝试逐插件资格,只有本次启动令牌可穿过启动屏障。
|
||||
"""
|
||||
normalized_id = self._normalize(plugin_id)
|
||||
if not normalized_id:
|
||||
raise ValueError("插件ID不能为空")
|
||||
@@ -52,24 +66,36 @@ class PluginLifecycleCoordinator:
|
||||
):
|
||||
return False
|
||||
self._active_plugins.add(normalized_id)
|
||||
self._started_at[normalized_id] = time.monotonic()
|
||||
return True
|
||||
|
||||
def _release_plugin(self, plugin_id: str) -> None:
|
||||
"""
|
||||
在实际执行结束后释放插件资格并移除耗时记录。
|
||||
"""
|
||||
normalized_id = self._normalize(plugin_id)
|
||||
with self._condition:
|
||||
self._active_plugins.discard(normalized_id)
|
||||
self._started_at.pop(normalized_id, None)
|
||||
self._condition.notify_all()
|
||||
|
||||
def _try_acquire_startup(self) -> PluginStartupLease | None:
|
||||
"""
|
||||
仅在没有启动或逐插件持有者时签发启动租约。
|
||||
"""
|
||||
with self._condition:
|
||||
if self._startup_active or self._active_plugins:
|
||||
return None
|
||||
startup_token = PluginStartupLease()
|
||||
self._startup_active = True
|
||||
self._startup_started_at = time.monotonic()
|
||||
self._startup_token = startup_token
|
||||
return startup_token
|
||||
|
||||
def _release_startup(self, startup_token: PluginStartupLease) -> None:
|
||||
"""
|
||||
仅由当前租约令牌释放启动屏障,避免旧清理误放行。
|
||||
"""
|
||||
with self._condition:
|
||||
# 延迟清理不得释放已经由新持有者持有的启动租约。
|
||||
if self._startup_token is not startup_token:
|
||||
@@ -78,33 +104,67 @@ class PluginLifecycleCoordinator:
|
||||
self._startup_active = False
|
||||
self._condition.notify_all()
|
||||
|
||||
def _busy_reason(self) -> str:
|
||||
"""
|
||||
返回当前启动或逐插件资格的持有者及持续秒数。
|
||||
"""
|
||||
with self._condition:
|
||||
owners = dict(self._started_at)
|
||||
if self._startup_active:
|
||||
owners["启动同步"] = self._startup_started_at
|
||||
now = time.monotonic()
|
||||
details = "、".join(f"{owner} 已执行 {now - started:.2f} 秒" for owner, started in owners.items())
|
||||
return f"插件生命周期准入正忙:{details}"
|
||||
|
||||
@asynccontextmanager
|
||||
async def hold(
|
||||
self,
|
||||
plugin_id: str,
|
||||
startup_token: PluginStartupLease | None = None,
|
||||
*,
|
||||
timeout: float = 5.0,
|
||||
) -> AsyncIterator[None]:
|
||||
"""
|
||||
异步持有单个插件的生命周期资格,不在线程池中等待锁。
|
||||
按预算异步等待单插件资格,超时不释放现有持有者。
|
||||
|
||||
:param plugin_id: 需要取得执行资格的源码插件 ID
|
||||
:param startup_token: 当前启动租约令牌;外部请求无需传入
|
||||
:param timeout: 最长准入等待秒数,默认 5 秒
|
||||
:raises PluginMutationRejectedError: 超时仍未获准,操作尚未执行
|
||||
"""
|
||||
deadline = time.monotonic() + max(0.0, timeout)
|
||||
while not self._try_acquire_plugin(plugin_id, startup_token):
|
||||
await asyncio.sleep(0.01)
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise PluginMutationRejectedError(f"操作插件 {plugin_id}", self._busy_reason())
|
||||
await asyncio.sleep(min(0.01, remaining))
|
||||
if time.monotonic() >= deadline:
|
||||
raise PluginMutationRejectedError(f"操作插件 {plugin_id}", self._busy_reason())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._release_plugin(plugin_id)
|
||||
|
||||
@asynccontextmanager
|
||||
async def hold_startup(self) -> AsyncIterator[PluginStartupLease]:
|
||||
async def hold_startup(self, *, timeout: float = 5.0) -> AsyncIterator[PluginStartupLease]:
|
||||
"""
|
||||
异步持有启动同步的全局资格,阻止安装请求穿过启动收口。
|
||||
有界取得启动同步资格,阻止安装请求穿过启动收口。
|
||||
|
||||
:param timeout: 最长准入等待秒数,默认 5 秒
|
||||
:raises PluginMutationRejectedError: 预算耗尽时仍有真实持有者
|
||||
"""
|
||||
deadline = time.monotonic() + max(0.0, timeout)
|
||||
startup_token: PluginStartupLease | None = None
|
||||
while startup_token is None:
|
||||
startup_token = self._try_acquire_startup()
|
||||
if startup_token is not None:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise PluginMutationRejectedError("启动同步插件", self._busy_reason())
|
||||
await asyncio.sleep(min(0.01, remaining))
|
||||
if time.monotonic() >= deadline:
|
||||
raise PluginMutationRejectedError("启动同步插件", self._busy_reason())
|
||||
try:
|
||||
yield startup_token
|
||||
finally:
|
||||
|
||||
@@ -5,12 +5,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
import time
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
from app.schemas.plugin import PluginLifecycleActivity
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -19,11 +22,15 @@ class _MutationContext:
|
||||
记录一个可跨协程和受控线程传播的事务上下文。
|
||||
|
||||
:param admission: 负责本次变更事务准入的控制器
|
||||
:param operation: 根事务的操作说明
|
||||
:param started_at: 根事务开始的单调时钟秒数
|
||||
:param holders: 持有该上下文的调用数,初始为 0
|
||||
:param open: 上下文是否仍接受后续持有者,初始为 True
|
||||
"""
|
||||
|
||||
admission: "PluginMutationAdmission"
|
||||
operation: str
|
||||
started_at: float
|
||||
holders: int = 0
|
||||
open: bool = True
|
||||
|
||||
@@ -33,13 +40,17 @@ class PluginMutationAdmission:
|
||||
在停机封口与插件可变事务之间维护真实 owner 计数。
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
def __init__(
|
||||
self, activity: Optional[Callable[[], Optional[PluginLifecycleActivity]]] = None,
|
||||
) -> None:
|
||||
"""
|
||||
初始化开放准入、活动 owner 计数和事务上下文。
|
||||
"""
|
||||
self._condition = threading.Condition()
|
||||
self._accepting = True
|
||||
self._active_count = 0
|
||||
self._owner: Optional[_MutationContext] = None
|
||||
self._lifecycle_activity = activity or (lambda: None)
|
||||
self._current_context: ContextVar[_MutationContext | None] = ContextVar(
|
||||
"plugin_mutation_context",
|
||||
default=None,
|
||||
@@ -77,7 +88,10 @@ class PluginMutationAdmission:
|
||||
@contextmanager
|
||||
def hold(self, operation: str) -> Iterator[None]:
|
||||
"""
|
||||
取得可变事务 lease;封口后仅允许已获准事务的嵌套调用。
|
||||
取得完整变更事务的执行权;竞争者快速拒绝,嵌套调用沿用真实 owner。
|
||||
|
||||
共享源码导入、注册表及补偿流程需要串行执行。执行权在副作用前取得,
|
||||
避免保存配置或替换源码之后才因生命周期繁忙失败;不在事件循环中等同步锁。
|
||||
"""
|
||||
context = self._current_context.get()
|
||||
context_token = None
|
||||
@@ -93,7 +107,17 @@ class PluginMutationAdmission:
|
||||
if not self._accepting and not nested:
|
||||
raise PluginMutationRejectedError(operation)
|
||||
if not nested:
|
||||
context = _MutationContext(admission=self)
|
||||
if self._owner is not None:
|
||||
activity = self.activity()
|
||||
assert activity is not None
|
||||
raise PluginMutationRejectedError(
|
||||
operation,
|
||||
f"插件变更正忙:{activity.plugin_id or activity.operation} "
|
||||
f"{activity.hook or activity.operation} "
|
||||
f"已执行 {activity.elapsed_seconds:.2f} 秒",
|
||||
)
|
||||
context = _MutationContext(self, operation, time.monotonic())
|
||||
self._owner = context
|
||||
context_token = self._current_context.set(context)
|
||||
assert context is not None
|
||||
self._active_count += 1
|
||||
@@ -109,6 +133,8 @@ class PluginMutationAdmission:
|
||||
context.holders -= 1
|
||||
if context.holders == 0:
|
||||
context.open = False
|
||||
if self._owner is context:
|
||||
self._owner = None
|
||||
self._condition.notify_all()
|
||||
if context_token is not None:
|
||||
self._current_context.reset(context_token)
|
||||
@@ -121,13 +147,33 @@ class PluginMutationAdmission:
|
||||
self._accepting = False
|
||||
return self._active_count
|
||||
|
||||
def wait_until_idle(self) -> None:
|
||||
def activity(self) -> Optional[PluginLifecycleActivity]:
|
||||
"""
|
||||
自然等待全部已获准 lease 退出,不取消或遗失其 owner。
|
||||
返回真实根事务或其正在执行的钩子,调用方超时不会清除此记录。
|
||||
"""
|
||||
with self._condition:
|
||||
if self._owner is None:
|
||||
return None
|
||||
return self._lifecycle_activity() or PluginLifecycleActivity(
|
||||
operation=self._owner.operation,
|
||||
elapsed_seconds=time.monotonic() - self._owner.started_at,
|
||||
)
|
||||
|
||||
def wait_until_idle(self, timeout: Optional[float] = None) -> bool:
|
||||
"""
|
||||
按预算等待已获准 lease 退出;超时不取消或释放真实 owner。
|
||||
|
||||
:param timeout: 最长等待秒数;为空时保留兼容的自然等待语义
|
||||
:return: 所有 lease 均已退出时为 True,预算耗尽时为 False
|
||||
"""
|
||||
deadline = None if timeout is None else time.monotonic() + max(0.0, timeout)
|
||||
with self._condition:
|
||||
while self._active_count:
|
||||
self._condition.wait()
|
||||
remaining = None if deadline is None else deadline - time.monotonic()
|
||||
if remaining is not None and remaining <= 0:
|
||||
return False
|
||||
self._condition.wait(timeout=remaining)
|
||||
return True
|
||||
|
||||
def reopen(self) -> bool:
|
||||
"""
|
||||
|
||||
89
app/runtime/extensions/plugin/gate.py
Normal file
89
app/runtime/extensions/plugin/gate.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
插件生命周期的互斥执行权和慢钩子诊断,仅在更新所有权时短暂持锁。
|
||||
"""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
from app.schemas.plugin import PluginLifecycleActivity
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Operation:
|
||||
"""
|
||||
同一执行线程内嵌套的生命周期操作或钩子。
|
||||
|
||||
:param operation: 操作名称
|
||||
:param plugin_id: 当前处理的插件 ID;全局准备阶段为空
|
||||
:param hook: 当前钩子或加载阶段;未进入时为空
|
||||
:param started_at: 单调时钟记录的进入时刻,单位为秒
|
||||
"""
|
||||
|
||||
operation: str
|
||||
plugin_id: Optional[str]
|
||||
hook: Optional[str]
|
||||
started_at: float
|
||||
|
||||
|
||||
class PluginLifecycleGate:
|
||||
"""
|
||||
保留共享注册表的串行约束,竞争者立即拒绝,不持锁运行第三方代码。
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
初始化执行线程归属与嵌套操作栈。
|
||||
"""
|
||||
self._lock = threading.RLock()
|
||||
self._thread_id: Optional[int] = None
|
||||
self._operations: list[_Operation] = []
|
||||
|
||||
@contextmanager
|
||||
def hold(
|
||||
self, operation: str, plugin_id: Optional[str] = None, hook: Optional[str] = None,
|
||||
) -> Iterator[None]:
|
||||
"""
|
||||
为当前线程取得执行权,允许同步停启嵌套,其他线程快速失败。
|
||||
|
||||
:raises PluginMutationRejectedError: 另一个线程仍持有真实执行权
|
||||
"""
|
||||
current_thread = threading.get_ident()
|
||||
with self._lock:
|
||||
if self._operations and self._thread_id != current_thread:
|
||||
activity = self.activity()
|
||||
assert activity is not None
|
||||
raise PluginMutationRejectedError(
|
||||
operation,
|
||||
f"插件生命周期正忙:{activity.plugin_id or '全部插件'} "
|
||||
f"{activity.operation}/{activity.hook or '准备'} "
|
||||
f"已执行 {activity.elapsed_seconds:.2f} 秒",
|
||||
)
|
||||
self._thread_id = current_thread
|
||||
self._operations.append(_Operation(operation, plugin_id, hook, time.monotonic()))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
with self._lock:
|
||||
self._operations.pop()
|
||||
if not self._operations:
|
||||
self._thread_id = None
|
||||
|
||||
def activity(self) -> Optional[PluginLifecycleActivity]:
|
||||
"""
|
||||
返回当前真实执行者及钩子耗时,不等待其第三方代码完成。
|
||||
"""
|
||||
with self._lock:
|
||||
if not self._operations:
|
||||
return None
|
||||
root, current = self._operations[0], self._operations[-1]
|
||||
now = time.monotonic()
|
||||
return PluginLifecycleActivity(
|
||||
operation=root.operation, plugin_id=current.plugin_id,
|
||||
hook=current.hook, elapsed_seconds=now - root.started_at,
|
||||
hook_elapsed_seconds=now - current.started_at if current.hook else 0,
|
||||
)
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from collections.abc import Callable
|
||||
@@ -13,6 +12,7 @@ from pathlib import Path
|
||||
from typing import Any, Optional, ParamSpec, TypeVar, cast
|
||||
|
||||
from app.runtime.extensions.plugin.database import PluginDatabase
|
||||
from app.runtime.extensions.plugin.gate import PluginLifecycleGate
|
||||
from app.runtime.extensions.plugin.gil import (
|
||||
GilFallbackRecorder,
|
||||
attribute_gil_fallback,
|
||||
@@ -20,7 +20,7 @@ from app.runtime.extensions.plugin.gil import (
|
||||
)
|
||||
from app.runtime.log import bind_plugin_instance
|
||||
from app.runtime.observability import record_metric
|
||||
from app.schemas.plugin import PluginRuntimeStatus
|
||||
from app.schemas.plugin import PluginLifecycleActivity, PluginRuntimeStatus
|
||||
|
||||
P = ParamSpec("P")
|
||||
R = TypeVar("R")
|
||||
@@ -124,9 +124,15 @@ class PluginLifecycle:
|
||||
self._enabled_state_recorder = enabled_state_recorder or (
|
||||
lambda _plugin_id: None
|
||||
)
|
||||
self._lifecycle_lock = threading.RLock()
|
||||
self._gate = PluginLifecycleGate()
|
||||
self._quiesced_hooks: dict[str, set[str]] = {}
|
||||
|
||||
def activity(self) -> Optional[PluginLifecycleActivity]:
|
||||
"""
|
||||
返回仍在执行的操作和钩子,不等待插件退出。
|
||||
"""
|
||||
return self._gate.activity()
|
||||
|
||||
@observe_plugin_lifecycle("start")
|
||||
def start(
|
||||
self,
|
||||
@@ -135,12 +141,12 @@ class PluginLifecycle:
|
||||
"""
|
||||
加载并初始化插件,返回每个目标的明确运行结果。
|
||||
|
||||
与 stop/quiesce 共用同一把可重入锁。加载要构造实例、建库并注册事件订阅,
|
||||
与 stop/quiesce 共用可重入执行权,竞争者在副作用前拒绝。加载要构造实例、建库并注册事件订阅,
|
||||
停止取的却是进入时的运行表快照:两者交叠时,本次加载的实例落在快照之外而
|
||||
停止仍会把它从运行表里抹掉,它注册的定时任务、线程和事件订阅却留在原处,
|
||||
此后没有任何句柄能再停掉它。
|
||||
"""
|
||||
with self._lifecycle_lock:
|
||||
with self._gate.hold("start", plugin_id):
|
||||
loadable_plugins = self._loadable_plugins()
|
||||
results: dict[str, PluginRuntimeStatus] = {}
|
||||
if plugin_id:
|
||||
@@ -152,7 +158,8 @@ class PluginLifecycle:
|
||||
"""
|
||||
return hasattr(module, "init_plugin") and hasattr(module, "plugin_name")
|
||||
|
||||
plugins = self._load_plugins(plugin_id, loadable_plugins, check_module)
|
||||
with self._gate.hold("start", plugin_id, "load"):
|
||||
plugins = self._load_plugins(plugin_id, loadable_plugins, check_module)
|
||||
plugins.sort(key=lambda item: getattr(item, "plugin_order", 0))
|
||||
for plugin in plugins:
|
||||
current_id = plugin.__name__
|
||||
@@ -185,11 +192,15 @@ class PluginLifecycle:
|
||||
current_id,
|
||||
self._gil_fallback_recorder,
|
||||
):
|
||||
instance = plugin()
|
||||
with self._gate.hold("start", current_id, "__init__"):
|
||||
instance = plugin()
|
||||
self._running[current_id] = instance
|
||||
instance.init_plugin(self._plugin_config(current_id))
|
||||
self._ensure_database(current_id, instance)
|
||||
enabled = bool(instance.get_state())
|
||||
with self._gate.hold("start", current_id, "init_plugin"):
|
||||
instance.init_plugin(self._plugin_config(current_id))
|
||||
with self._gate.hold("start", current_id, "database"):
|
||||
self._ensure_database(current_id, instance)
|
||||
with self._gate.hold("start", current_id, "get_state"):
|
||||
enabled = bool(instance.get_state())
|
||||
if enabled:
|
||||
self._refresh_classification_safely(current_id, instance)
|
||||
else:
|
||||
@@ -290,27 +301,30 @@ class PluginLifecycle:
|
||||
"""
|
||||
重新应用指定插件配置并刷新事件注册状态。
|
||||
"""
|
||||
plugin = self._running.get(plugin_id)
|
||||
if not plugin:
|
||||
return
|
||||
was_enabled = bool(plugin.get_state())
|
||||
self._remove_classification(plugin_id)
|
||||
try:
|
||||
with bind_plugin_instance(plugin_id):
|
||||
plugin.init_plugin(config)
|
||||
enabled = bool(plugin.get_state())
|
||||
if enabled:
|
||||
self._refresh_classification_safely(plugin_id, plugin)
|
||||
self._enable_events(type(plugin))
|
||||
else:
|
||||
self._remove_classification(plugin_id)
|
||||
self._disable_events(type(plugin))
|
||||
except Exception:
|
||||
with self._gate.hold("initialize", plugin_id):
|
||||
plugin = self._running.get(plugin_id)
|
||||
if not plugin:
|
||||
return
|
||||
with self._gate.hold("initialize", plugin_id, "get_state"):
|
||||
was_enabled = bool(plugin.get_state())
|
||||
self._remove_classification(plugin_id)
|
||||
raise
|
||||
self._clear_tools()
|
||||
if enabled != was_enabled:
|
||||
self._enabled_state_recorder(plugin_id)
|
||||
try:
|
||||
with bind_plugin_instance(plugin_id), self._gate.hold("initialize", plugin_id, "init_plugin"):
|
||||
plugin.init_plugin(config)
|
||||
with self._gate.hold("initialize", plugin_id, "get_state"):
|
||||
enabled = bool(plugin.get_state())
|
||||
if enabled:
|
||||
self._refresh_classification_safely(plugin_id, plugin)
|
||||
self._enable_events(type(plugin))
|
||||
else:
|
||||
self._remove_classification(plugin_id)
|
||||
self._disable_events(type(plugin))
|
||||
except Exception:
|
||||
self._remove_classification(plugin_id)
|
||||
raise
|
||||
self._clear_tools()
|
||||
if enabled != was_enabled:
|
||||
self._enabled_state_recorder(plugin_id)
|
||||
|
||||
def _refresh_classification_safely(
|
||||
self,
|
||||
@@ -337,7 +351,7 @@ class PluginLifecycle:
|
||||
:param plugin_id: 指定插件标识;为空时停止全部实例
|
||||
:return: 停止或卸载失败时为False,成功时保留旧ABI的None
|
||||
"""
|
||||
with self._lifecycle_lock:
|
||||
with self._gate.hold("stop", plugin_id):
|
||||
plugins = self._select_running_plugins(plugin_id)
|
||||
if not self._quiesce_selected(plugins):
|
||||
self._record_stop_failure(plugins)
|
||||
@@ -365,7 +379,7 @@ class PluginLifecycle:
|
||||
"""
|
||||
先解绑事件 handler,再按旧 hook 顺序停止生产者并保留实例。
|
||||
"""
|
||||
with self._lifecycle_lock:
|
||||
with self._gate.hold("quiesce", plugin_id):
|
||||
plugins = self._select_running_plugins(plugin_id)
|
||||
return self._quiesce_selected(plugins)
|
||||
|
||||
@@ -374,7 +388,7 @@ class PluginLifecycle:
|
||||
"""
|
||||
禁止目标插件接收新事件,保留实例供在途 handler 和后续 hook 使用。
|
||||
"""
|
||||
with self._lifecycle_lock:
|
||||
with self._gate.hold("quiesce_handlers", plugin_id):
|
||||
plugins = self._select_running_plugins(plugin_id)
|
||||
return self._disable_selected_handlers(plugins)
|
||||
|
||||
@@ -383,7 +397,7 @@ class PluginLifecycle:
|
||||
"""
|
||||
在事件结算屏障后执行旧 close、stop_service hook。
|
||||
"""
|
||||
with self._lifecycle_lock:
|
||||
with self._gate.hold("quiesce_services", plugin_id):
|
||||
plugins = self._select_running_plugins(plugin_id)
|
||||
if not self._handlers_quiesced(plugins):
|
||||
self._logger.warning("插件事件 handler 尚未全部停用,拒绝关闭插件资源")
|
||||
@@ -434,7 +448,8 @@ class PluginLifecycle:
|
||||
completed.add(hook_name)
|
||||
continue
|
||||
try:
|
||||
result = hook()
|
||||
with self._gate.hold("quiesce_services", current_id, hook_name):
|
||||
result = hook()
|
||||
# 插件边界必须隔离
|
||||
except Exception as error: # noqa: BLE001
|
||||
all_converged = False
|
||||
@@ -472,7 +487,7 @@ class PluginLifecycle:
|
||||
"""
|
||||
按严格或兼容策略卸载插件,并在清理失败时保留实例所有权。
|
||||
"""
|
||||
with self._lifecycle_lock:
|
||||
with self._gate.hold("finalize", plugin_id):
|
||||
plugins = self._select_running_plugins(plugin_id)
|
||||
if require_quiesced and any(
|
||||
not self._is_quiesced(current_id, plugin)
|
||||
@@ -564,7 +579,7 @@ class PluginLifecycle:
|
||||
"""
|
||||
重启指定插件并返回本次加载结果。
|
||||
"""
|
||||
with self._lifecycle_lock:
|
||||
with self._gate.hold("reload", plugin_id):
|
||||
self._runtime_status_writer(plugin_id, PluginRuntimeStatus.READY)
|
||||
if self.stop(plugin_id) is False:
|
||||
self._runtime_status_writer(plugin_id, PluginRuntimeStatus.LOAD_FAILED)
|
||||
|
||||
@@ -54,7 +54,7 @@ from app.schemas.category import ClassificationFactValue, ClassificationFieldDef
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
from app.schemas.plugin import Plugin as _SchemaPlugin
|
||||
from app.schemas.plugin import PluginDashboard as _SchemaPluginDashboard
|
||||
from app.schemas.plugin import PluginInstance, PluginRuntimeStatus
|
||||
from app.schemas.plugin import PluginInstance, PluginLifecycleActivity, PluginRuntimeStatus
|
||||
from app.schemas.types import EventType
|
||||
|
||||
LegacyDiagnosticsConfigurator = Callable[..., None]
|
||||
@@ -243,6 +243,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
self._suppressed_monitor_plugins: Dict[str, int] = {}
|
||||
self._monitor_suppressed_until: Dict[str, float] = {}
|
||||
self._plugin_quiesce_lock = threading.RLock()
|
||||
# 仅保护停机状态和 Future 引用;禁止在此锁内调用第三方生命周期。
|
||||
self._plugin_quiesce_future: Optional[
|
||||
concurrent.futures.Future[bool]
|
||||
] = None
|
||||
@@ -323,20 +324,19 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
|
||||
try:
|
||||
with self.mutation("启动插件"):
|
||||
with self._plugin_quiesce_lock:
|
||||
_legacy_diagnostics_configurator(
|
||||
enabled=get_runtime_setting('DEBUG'),
|
||||
emitter=logger.warning,
|
||||
_legacy_diagnostics_configurator(
|
||||
enabled=get_runtime_setting('DEBUG'),
|
||||
emitter=logger.warning,
|
||||
)
|
||||
gil_enabled_before = is_gil_enabled()
|
||||
try:
|
||||
return self._plugin_lifecycle.start(pid)
|
||||
finally:
|
||||
_warn_if_plugin_enabled_gil(
|
||||
gil_enabled_before=gil_enabled_before,
|
||||
plugin_id=pid,
|
||||
registry=self._plugin_registry,
|
||||
)
|
||||
gil_enabled_before = is_gil_enabled()
|
||||
try:
|
||||
return self._plugin_lifecycle.start(pid)
|
||||
finally:
|
||||
_warn_if_plugin_enabled_gil(
|
||||
gil_enabled_before=gil_enabled_before,
|
||||
plugin_id=pid,
|
||||
registry=self._plugin_registry,
|
||||
)
|
||||
except PluginMutationRejectedError as error:
|
||||
logger.warning(str(error))
|
||||
if pid:
|
||||
@@ -352,8 +352,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
try:
|
||||
with self.mutation("初始化插件配置"):
|
||||
with self._plugin_quiesce_lock:
|
||||
self._plugin_lifecycle.initialize(plugin_id, conf)
|
||||
self._plugin_lifecycle.initialize(plugin_id, conf)
|
||||
except PluginMutationRejectedError as error:
|
||||
logger.warning(str(error))
|
||||
|
||||
@@ -384,9 +383,8 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
try:
|
||||
with self.mutation("停止插件"):
|
||||
with self._plugin_quiesce_lock:
|
||||
if self._plugin_lifecycle.stop(pid) is False:
|
||||
return False
|
||||
if self._plugin_lifecycle.stop(pid) is False:
|
||||
return False
|
||||
except PluginMutationRejectedError as error:
|
||||
logger.warning(str(error))
|
||||
return False
|
||||
@@ -398,6 +396,12 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
return self._plugin_mutation_admission.hold(operation)
|
||||
|
||||
def get_plugin_lifecycle_activity(self) -> Optional[PluginLifecycleActivity]:
|
||||
"""
|
||||
只读返回仍持有执行权的插件、操作及钩子耗时。
|
||||
"""
|
||||
return self._plugin_lifecycle.activity() or self._plugin_mutation_admission.activity()
|
||||
|
||||
def reopen_plugins(self) -> bool:
|
||||
"""
|
||||
为新应用生命周期解除运行时封口,仍活跃的 quiesce owner 禁止复用。
|
||||
@@ -421,8 +425,9 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
|
||||
async def quiesce_plugins(self, timeout: float = 240.0) -> bool:
|
||||
"""
|
||||
封口变更事务并停用插件 handler,超时后保留 Future ownership。
|
||||
在同一预算内封口、等待变更并停用 handler;超时保留实际执行者。
|
||||
"""
|
||||
deadline = time.monotonic() + max(0.0, timeout)
|
||||
if self._plugin_mutation_admission.is_held():
|
||||
logger.warning("插件可变事务不能等待自身收敛,拒绝在事务内执行停机")
|
||||
return False
|
||||
@@ -431,12 +436,15 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
self._plugin_mutation_admission.seal()
|
||||
future = self._plugin_quiesce_future
|
||||
if future is None or future.done():
|
||||
future = ThreadHelper().submit(self._quiesce_after_mutations)
|
||||
future = ThreadHelper().submit(
|
||||
self._quiesce_after_mutations,
|
||||
deadline,
|
||||
)
|
||||
self._plugin_quiesce_future = future
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.shield(asyncio.wrap_future(future)),
|
||||
timeout=max(0.0, timeout),
|
||||
timeout=max(0.0, deadline - time.monotonic()),
|
||||
)
|
||||
return bool(result)
|
||||
except asyncio.TimeoutError:
|
||||
@@ -456,6 +464,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
在事件结算后执行旧插件停机 hook,并有界等待同步 owner。
|
||||
"""
|
||||
deadline = time.monotonic() + max(0.0, timeout)
|
||||
with self._plugin_quiesce_lock:
|
||||
prepare_future = self._plugin_quiesce_future
|
||||
if prepare_future is not None and not prepare_future.done():
|
||||
@@ -476,7 +485,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.shield(asyncio.wrap_future(future)),
|
||||
timeout=max(0.0, timeout),
|
||||
timeout=max(0.0, deadline - time.monotonic()),
|
||||
)
|
||||
return bool(result)
|
||||
except asyncio.TimeoutError:
|
||||
@@ -507,13 +516,25 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
if self._plugin_mutation_admission.active_count:
|
||||
logger.warning("插件可变事务仍在执行,拒绝释放运行实例")
|
||||
return False
|
||||
return self._plugin_lifecycle.finalize()
|
||||
try:
|
||||
return self._plugin_lifecycle.finalize()
|
||||
except PluginMutationRejectedError as error:
|
||||
logger.warning(str(error))
|
||||
return False
|
||||
|
||||
def _quiesce_after_mutations(self) -> bool:
|
||||
def _quiesce_after_mutations(self, deadline: float) -> bool:
|
||||
"""
|
||||
等待已获准变更自然结束后,再停用插件事件入口。
|
||||
按预算等待已获准变更,再停用事件入口;不取消仍在运行的变更。
|
||||
|
||||
:param deadline: 从异步入口开始计算的单调时钟截止秒数,包含线程池排队
|
||||
"""
|
||||
self._plugin_mutation_admission.wait_until_idle()
|
||||
if not self._plugin_mutation_admission.wait_until_idle(
|
||||
timeout=max(0.0, deadline - time.monotonic()),
|
||||
):
|
||||
logger.warning(f"插件变更未收敛:{self.get_plugin_lifecycle_activity()}")
|
||||
return False
|
||||
if time.monotonic() >= deadline:
|
||||
return False
|
||||
return self._plugin_lifecycle.quiesce_handlers()
|
||||
|
||||
@property
|
||||
@@ -708,10 +729,9 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
try:
|
||||
with self.mutation("移除插件实例"):
|
||||
with self._plugin_quiesce_lock:
|
||||
if self._plugin_lifecycle.stop(plugin_id) is False:
|
||||
return False
|
||||
self._plugin_registry.remove(plugin_id)
|
||||
if self._plugin_lifecycle.stop(plugin_id) is False:
|
||||
return False
|
||||
self._plugin_registry.remove(plugin_id)
|
||||
except PluginMutationRejectedError as error:
|
||||
logger.warning(str(error))
|
||||
return False
|
||||
@@ -731,19 +751,18 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
try:
|
||||
with self.mutation("重新加载插件"):
|
||||
with self._plugin_quiesce_lock:
|
||||
gil_enabled_before = is_gil_enabled()
|
||||
try:
|
||||
return self._plugin_lifecycle.reload(
|
||||
plugin_id,
|
||||
EventType.PluginReload,
|
||||
)
|
||||
finally:
|
||||
_warn_if_plugin_enabled_gil(
|
||||
gil_enabled_before=gil_enabled_before,
|
||||
plugin_id=plugin_id,
|
||||
registry=self._plugin_registry,
|
||||
)
|
||||
gil_enabled_before = is_gil_enabled()
|
||||
try:
|
||||
return self._plugin_lifecycle.reload(
|
||||
plugin_id,
|
||||
EventType.PluginReload,
|
||||
)
|
||||
finally:
|
||||
_warn_if_plugin_enabled_gil(
|
||||
gil_enabled_before=gil_enabled_before,
|
||||
plugin_id=plugin_id,
|
||||
registry=self._plugin_registry,
|
||||
)
|
||||
except PluginMutationRejectedError as error:
|
||||
logger.warning(str(error))
|
||||
return PluginRuntimeStatus.LOAD_FAILED
|
||||
@@ -754,12 +773,11 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
try:
|
||||
with self.mutation("重载插件实例树"):
|
||||
with self._plugin_quiesce_lock:
|
||||
source_plugin_id = self.get_plugin_source_id(plugin_id)
|
||||
status = self.reload_plugin(source_plugin_id)
|
||||
for instance in self._plugin_instance_store.for_source(source_plugin_id):
|
||||
self.reload_plugin(instance.instance_id)
|
||||
return status
|
||||
source_plugin_id = self.get_plugin_source_id(plugin_id)
|
||||
status = self.reload_plugin(source_plugin_id)
|
||||
for instance in self._plugin_instance_store.for_source(source_plugin_id):
|
||||
self.reload_plugin(instance.instance_id)
|
||||
return status
|
||||
except PluginMutationRejectedError as error:
|
||||
logger.warning(str(error))
|
||||
return PluginRuntimeStatus.LOAD_FAILED
|
||||
|
||||
@@ -561,7 +561,7 @@ def build_plugin_runtime(
|
||||
runner=host._run_file_watcher,
|
||||
log=environment.logger,
|
||||
),
|
||||
admission=PluginMutationAdmission(),
|
||||
admission=PluginMutationAdmission(activity=lifecycle.activity),
|
||||
dependencies=dependencies,
|
||||
loader=loader,
|
||||
tools=tools,
|
||||
|
||||
@@ -71,15 +71,18 @@ class OperationInterrupted(KeyboardInterrupt):
|
||||
|
||||
class PluginMutationRejectedError(RuntimeError):
|
||||
"""
|
||||
表示插件运行时已封口,新的可变事务未获准执行。
|
||||
表示插件运行时已封口或正忙,当前操作未获准执行。
|
||||
"""
|
||||
|
||||
def __init__(self, operation: str) -> None:
|
||||
def __init__(self, operation: str, reason: str = "插件运行时已进入停机阶段") -> None:
|
||||
"""
|
||||
保存被拒绝的操作名称并生成稳定诊断消息。
|
||||
|
||||
:param operation: 尚未取得执行权的操作
|
||||
:param reason: 拒绝原因,可包含持有方信息,不包含插件配置
|
||||
"""
|
||||
self.operation = operation
|
||||
super().__init__(f"插件运行时已进入停机阶段,拒绝{operation}")
|
||||
super().__init__(f"{reason},拒绝{operation}")
|
||||
|
||||
|
||||
class StorageQueryError(Exception):
|
||||
|
||||
@@ -376,6 +376,7 @@ SCHEMA_EXPORTS = {
|
||||
'PluginInstanceLogLevelUpdateRequest': ('app.schemas.plugin', 'PluginInstanceLogLevelUpdateRequest'),
|
||||
'PluginInstancePurgeOutcome': ('app.schemas.plugin', 'PluginInstancePurgeOutcome'),
|
||||
'PluginInstancePurgeRequest': ('app.schemas.plugin', 'PluginInstancePurgeRequest'),
|
||||
'PluginLifecycleActivity': ('app.schemas.plugin', 'PluginLifecycleActivity'),
|
||||
'PluginMarketSyncData': ('app.schemas.system', 'PluginMarketSyncData'),
|
||||
'PluginMarketSyncRequest': ('app.schemas.system', 'PluginMarketSyncRequest'),
|
||||
'PluginMemoryInfo': ('app.schemas.plugin', 'PluginMemoryInfo'),
|
||||
|
||||
@@ -285,12 +285,24 @@ class PluginDocumentation(BaseModel):
|
||||
url: Optional[str] = Field(default=None, description="显式声明或已确认存在的 README 外链;不可用时为空")
|
||||
|
||||
|
||||
class PluginLifecycleActivity(BaseModel):
|
||||
"""
|
||||
当前仍持有执行权的插件操作,不包含配置或凭据。
|
||||
"""
|
||||
|
||||
operation: str = Field(description="正在执行的生命周期操作或变更事务")
|
||||
plugin_id: Optional[str] = Field(default=None, description="当前处理的插件 ID;全局操作准备阶段为空")
|
||||
hook: Optional[str] = Field(default=None, description="当前执行的插件钩子或加载阶段;未进入时为空")
|
||||
elapsed_seconds: float = Field(ge=0, description="本次操作已经持续的秒数")
|
||||
hook_elapsed_seconds: float = Field(default=0, ge=0, description="当前钩子已经持续的秒数")
|
||||
|
||||
|
||||
class PluginRuntimeSummary(BaseModel):
|
||||
"""
|
||||
插件后台收敛状态和前端刷新代次。
|
||||
"""
|
||||
|
||||
ready: bool = Field(description="本轮插件源码、依赖和加载是否已收敛")
|
||||
ready: bool = Field(description="本轮插件源码、依赖和加载已收敛,且没有在途变更或生命周期操作")
|
||||
generation: int = Field(description="插件运行状态变化代次")
|
||||
pending_count: int = Field(description="仍处于准备阶段的插件数量")
|
||||
failed_count: int = Field(description="加载失败或被策略阻止的插件数量")
|
||||
@@ -302,6 +314,10 @@ class PluginRuntimeSummary(BaseModel):
|
||||
default_factory=list,
|
||||
description="当前进程内加载时导致 free-threaded 运行时回退到 GIL 的插件 ID",
|
||||
)
|
||||
active_operation: Optional[PluginLifecycleActivity] = Field(
|
||||
default=None,
|
||||
description="仍持有执行权的插件操作;调用方超时后仍会保留,直至实际结束",
|
||||
)
|
||||
|
||||
|
||||
class PluginRuntimeCommandCapability(BaseModel):
|
||||
|
||||
@@ -815,13 +815,13 @@ flowchart LR
|
||||
|
||||
### 10.2 当前架构快照
|
||||
|
||||
以下是 2026-10-27 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照,
|
||||
以下是 2026-11-01 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照,
|
||||
不代表某个已发布镜像或正在运行的实例已经验证。
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1145 |
|
||||
| 内部导入边 | 9,904 |
|
||||
| Python 模块 | 1146 |
|
||||
| 内部导入边 | 9,913 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) |
|
||||
|
||||
@@ -12,6 +12,15 @@
|
||||
缺失或超时返回 `{"url":null}`,不要求先安装插件。本地来源只返回显式声明的链接。
|
||||
探测总时限为五秒,结果缓存五分钟;接口不返回文档正文,也不新增 Agent operation。
|
||||
|
||||
### 插件生命周期忙碌与超时
|
||||
|
||||
`plugin.runtime.status`(`GET /api/v1/plugin/runtime`)的可选 `active_operation` 返回当前
|
||||
`operation`、`plugin_id`、`hook`、`elapsed_seconds` 与 `hook_elapsed_seconds`;空值表示没有
|
||||
持有者。有在途变更或钩子时 `ready=false`,准备态数量仍由 `pending_count` 独立表达。
|
||||
插件变更竞争共享执行权时在副作用前明确拒绝;安装的逐插件或启动准入最多等待五秒。
|
||||
调用方超时、取消或停机超时不会终止第三方同步钩子,执行权、实例及数据库保留到真实结束。
|
||||
遇到执行结果未知时先只读检查此摘要及插件实际状态,不能仅凭超时重复提交变更。
|
||||
|
||||
### 订阅下载的提交来源
|
||||
|
||||
新产生的订阅下载在订阅活动和日志中区分“首次订阅”“洗版升级”或“全集洗版”。
|
||||
|
||||
@@ -1301,6 +1301,7 @@ driven workflow registration.
|
||||
| `app/runtime/extensions/module/manager.py` | Module discovery and lifecycle |
|
||||
| `app/runtime/extensions/plugin/manager.py` | Stable PluginManager ABI facade plus plugin discovery/lifecycle entrypoints; its constructor only consumes the startup-injected Runtime factory and does not build an environment or individual owner |
|
||||
| `app/runtime/extensions/plugin/runtime.py` | Frozen typed aggregate and construction primitive for plugin registry, lifecycle, catalog, dependency, monitor, projection, sync and package-system owners; it does not choose concrete startup dependencies |
|
||||
| `app/runtime/extensions/plugin/gate.py` | 插件生命周期的可重入执行权与钩子耗时快照;仅更新 owner 时持锁,竞争者立即拒绝,第三方代码在锁外执行;`admission.py` 在完整可变事务的副作用前取得同一运行时的根事务资格 |
|
||||
| `app/runtime/extensions/plugin/system.py` | Startup-injected market/package/dependency system-port facade, including delegation to the unique physical package deletion owner; it does not construct concrete adapters |
|
||||
| `app/runtime/extensions/plugin/dependency.py` | Virtual-instance dependency classification and runtime-status persistence owner |
|
||||
| `app/startup/initializers/plugins.py` | Plugin Runtime dependency-graph composition, concrete system/storage/catalog ports and lifecycle initialization |
|
||||
|
||||
@@ -17,7 +17,7 @@ PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
MOVIEPILOT_API_SKILL_VERSION = "70"
|
||||
MOVIEPILOT_API_SKILL_VERSION = "71"
|
||||
DATABASE_OPERATION_SKILL_VERSION = "17"
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: moviepilot-api
|
||||
version: 70
|
||||
version: 71
|
||||
description: >-
|
||||
Use this skill for MoviePilot product operations such as media search, torrent
|
||||
search, downloads, subscriptions, library checks, sites, storage, workflows,
|
||||
@@ -67,6 +67,11 @@ allowed-api-operations: >-
|
||||
|
||||
# MoviePilot API
|
||||
|
||||
When a plugin mutation is busy or its outcome is unknown, inspect `plugin.runtime.status`
|
||||
before retrying. `active_operation` identifies the running plugin, operation, hook, and
|
||||
elapsed time. A caller timeout or cancellation does not stop the hook and must never
|
||||
trigger automatic replay of the same mutation.
|
||||
|
||||
For a historical invalid plugin instance ID reported in logs, `plugin.instance.purge`
|
||||
accepts the exact ID with only `config: true` (all other scope flags false). It deletes
|
||||
only an empty disabled host record: no saved configuration, display overrides, default
|
||||
|
||||
@@ -959,8 +959,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 9904,
|
||||
"edge_sha256": "4fbaf07e93f98d96204ced4acdd8be21af9ac11e2a7c3aa9bbce1b4c0785a5b6",
|
||||
"edge_count": 9913,
|
||||
"edge_sha256": "b53a0ce9073ab55453a6f44ce5e40e4414039f5069720b10593be2bc8a7f661c",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -4048,6 +4048,8 @@
|
||||
"app.application.plugin.gateway -> app.application.plugin.source",
|
||||
"app.application.plugin.gateway -> app.domain",
|
||||
"app.application.plugin.gateway -> app.domain.plugin",
|
||||
"app.application.plugin.gateway -> app.schemas",
|
||||
"app.application.plugin.gateway -> app.schemas.exception",
|
||||
"app.application.plugin.identity -> app.application",
|
||||
"app.application.plugin.identity -> app.application.plugin",
|
||||
"app.application.plugin.identity -> app.application.plugin.declaration",
|
||||
@@ -4073,6 +4075,8 @@
|
||||
"app.application.plugin.inventory -> app.application.plugin.source",
|
||||
"app.application.plugin.inventory -> app.domain",
|
||||
"app.application.plugin.inventory -> app.domain.plugin",
|
||||
"app.application.plugin.lifecycle -> app.schemas",
|
||||
"app.application.plugin.lifecycle -> app.schemas.exception",
|
||||
"app.application.plugin.management -> app.application",
|
||||
"app.application.plugin.management -> app.application.commands",
|
||||
"app.application.plugin.management -> app.application.configuration",
|
||||
@@ -9197,6 +9201,7 @@
|
||||
"app.runtime.extensions.module.manager -> app.schemas.types",
|
||||
"app.runtime.extensions.plugin.admission -> app.schemas",
|
||||
"app.runtime.extensions.plugin.admission -> app.schemas.exception",
|
||||
"app.runtime.extensions.plugin.admission -> app.schemas.plugin",
|
||||
"app.runtime.extensions.plugin.catalog -> app.domain",
|
||||
"app.runtime.extensions.plugin.catalog -> app.domain.plugin",
|
||||
"app.runtime.extensions.plugin.catalog -> app.foundation",
|
||||
@@ -9234,12 +9239,16 @@
|
||||
"app.runtime.extensions.plugin.dependency -> app.runtime.extensions.plugin.system",
|
||||
"app.runtime.extensions.plugin.dependency -> app.schemas",
|
||||
"app.runtime.extensions.plugin.dependency -> app.schemas.plugin",
|
||||
"app.runtime.extensions.plugin.gate -> app.schemas",
|
||||
"app.runtime.extensions.plugin.gate -> app.schemas.exception",
|
||||
"app.runtime.extensions.plugin.gate -> app.schemas.plugin",
|
||||
"app.runtime.extensions.plugin.gil -> app.foundation",
|
||||
"app.runtime.extensions.plugin.gil -> app.foundation.environment",
|
||||
"app.runtime.extensions.plugin.lifecycle -> app.runtime",
|
||||
"app.runtime.extensions.plugin.lifecycle -> app.runtime.extensions",
|
||||
"app.runtime.extensions.plugin.lifecycle -> app.runtime.extensions.plugin",
|
||||
"app.runtime.extensions.plugin.lifecycle -> app.runtime.extensions.plugin.database",
|
||||
"app.runtime.extensions.plugin.lifecycle -> app.runtime.extensions.plugin.gate",
|
||||
"app.runtime.extensions.plugin.lifecycle -> app.runtime.extensions.plugin.gil",
|
||||
"app.runtime.extensions.plugin.lifecycle -> app.runtime.log",
|
||||
"app.runtime.extensions.plugin.lifecycle -> app.runtime.observability",
|
||||
@@ -10867,7 +10876,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1145,
|
||||
"module_count": 1146,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -11823,6 +11832,7 @@
|
||||
"app.runtime.extensions.plugin.database",
|
||||
"app.runtime.extensions.plugin.datadir",
|
||||
"app.runtime.extensions.plugin.dependency",
|
||||
"app.runtime.extensions.plugin.gate",
|
||||
"app.runtime.extensions.plugin.gil",
|
||||
"app.runtime.extensions.plugin.lifecycle",
|
||||
"app.runtime.extensions.plugin.loader",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"repeat": 3,
|
||||
"targets": {
|
||||
"app.startup.lifecycle": {
|
||||
"loaded_app_module_count": 597,
|
||||
"loaded_app_module_count": 598,
|
||||
"max_ms": 1293.338,
|
||||
"median_ms": 1156.239,
|
||||
"min_ms": 1102.806,
|
||||
@@ -17,7 +17,7 @@
|
||||
]
|
||||
},
|
||||
"app.factory": {
|
||||
"loaded_app_module_count": 611,
|
||||
"loaded_app_module_count": 612,
|
||||
"max_ms": 1127.911,
|
||||
"median_ms": 1122.382,
|
||||
"min_ms": 1119.221,
|
||||
@@ -28,7 +28,7 @@
|
||||
]
|
||||
},
|
||||
"app.main": {
|
||||
"loaded_app_module_count": 613,
|
||||
"loaded_app_module_count": 614,
|
||||
"max_ms": 1188.652,
|
||||
"median_ms": 1183.509,
|
||||
"min_ms": 1174.522,
|
||||
|
||||
@@ -130,7 +130,7 @@ def test_modified_builtin_skills_have_incremented_versions() -> None:
|
||||
"database-operation": "17",
|
||||
"feedback-issue": "12",
|
||||
"anysearch": "3",
|
||||
"moviepilot-api": "70",
|
||||
"moviepilot-api": "71",
|
||||
"moviepilot-update": "7",
|
||||
"organize-files": "6",
|
||||
"transfer-failed-retry": "6",
|
||||
|
||||
@@ -657,6 +657,7 @@ def test_runtime_status_reports_pending_and_terminal_counts():
|
||||
"RemovedPlugin": ("native-removed",),
|
||||
}
|
||||
plugin_manager.get_plugin_gil_fallbacks.return_value = ["NativePlugin", "RemovedPlugin"]
|
||||
plugin_manager.get_plugin_lifecycle_activity.return_value = None
|
||||
config = MagicMock()
|
||||
config.get.return_value = ["NativePlugin"]
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ from app.application.plugin.source import (
|
||||
PluginLocalCandidate,
|
||||
PluginMarketCandidate,
|
||||
)
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
|
||||
NOW = datetime(2026, 8, 25, 12, 0, tzinfo=timezone.utc)
|
||||
REPO_URL = "https://github.com/jxxghp/MoviePilot-Plugins"
|
||||
@@ -52,6 +53,34 @@ def _inventory() -> CandidateInventory:
|
||||
))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gateway_reports_lifecycle_busy_before_identity_or_install(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
生命周期准入预算耗尽时返回明确失败,不能继续读取身份或写入载荷。
|
||||
"""
|
||||
identity = AsyncMock()
|
||||
executor = AsyncMock()
|
||||
|
||||
monkeypatch.setattr(
|
||||
gateway_module.plugin_lifecycle, "hold",
|
||||
Mock(side_effect=PluginMutationRejectedError("安装 DemoPlugin", "插件生命周期准入正忙")),
|
||||
)
|
||||
gateway = PluginInstallGateway(
|
||||
inventory=AsyncMock(return_value=_inventory()), identity=identity,
|
||||
candidate_compatibility=lambda _candidate: (True, ""),
|
||||
executor=executor, clock=lambda: NOW,
|
||||
source_plugin_id=lambda plugin_id: plugin_id,
|
||||
)
|
||||
result = await gateway.install(plugin_id="DemoPlugin", repo_url=REPO_URL)
|
||||
assert result.success is False
|
||||
assert result.failure_stage == "admission"
|
||||
assert "准入正忙" in result.message
|
||||
identity.assert_not_awaited()
|
||||
executor.execute.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gateway_freezes_admission_before_executing_transaction() -> None:
|
||||
"""
|
||||
|
||||
239
tests/test_plugin_lifecycle_blocking.py
Normal file
239
tests/test_plugin_lifecycle_blocking.py
Normal file
@@ -0,0 +1,239 @@
|
||||
"""
|
||||
慢插件钩子的准入拒绝、停机预算和真实资源所有权回归测试。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from concurrent.futures import TimeoutError as FutureTimeoutError
|
||||
from contextlib import contextmanager
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.runtime.extensions.plugin.admission import PluginMutationAdmission
|
||||
from app.runtime.extensions.plugin.lifecycle import PluginLifecycle
|
||||
from app.runtime.extensions.plugin.manager import PluginManager
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _blocked_plugin(
|
||||
manager: Optional[PluginManager] = None, *, start: bool = True,
|
||||
) -> Iterator[SimpleNamespace]:
|
||||
"""
|
||||
在线程中阻塞真实 close 钩子,退出时始终放行并回收线程。
|
||||
"""
|
||||
entered = threading.Event()
|
||||
release = threading.Event()
|
||||
database = MagicMock()
|
||||
calls = []
|
||||
|
||||
class SlowPlugin:
|
||||
"""
|
||||
以可控事件模拟未返回的第三方资源关闭钩子。
|
||||
"""
|
||||
|
||||
def close(self) -> None:
|
||||
"""
|
||||
等待测试释放;兜底预算防止旧实现阻塞整个测试进程。
|
||||
"""
|
||||
entered.set()
|
||||
calls.append("close")
|
||||
assert release.wait(timeout=3)
|
||||
|
||||
instance = SlowPlugin()
|
||||
running = {"SlowPlugin": instance}
|
||||
lifecycle = PluginLifecycle(
|
||||
classes={"SlowPlugin": SlowPlugin}, running=running,
|
||||
load_plugins=lambda *_args: [], loadable_plugins=lambda: [],
|
||||
plugin_config=lambda _pid: {}, auth_checker=lambda _plugin: True,
|
||||
clear_modules=MagicMock(), clear_tools=MagicMock(),
|
||||
enable_events=MagicMock(), disable_events=MagicMock(),
|
||||
runtime_status_writer=MagicMock(), runtime_compatible=lambda _pid: True,
|
||||
database=lambda: database, log=MagicMock(), event_sender=MagicMock(),
|
||||
)
|
||||
if manager is not None:
|
||||
manager._plugin_lifecycle = lifecycle
|
||||
manager._running_plugins = running
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
stop = manager.stop if manager is not None else lifecycle.stop
|
||||
future = executor.submit(stop, "SlowPlugin") if start else None
|
||||
try:
|
||||
if start:
|
||||
assert entered.wait(timeout=1)
|
||||
yield SimpleNamespace(
|
||||
lifecycle=lifecycle, executor=executor, future=future,
|
||||
running=running, instance=instance, database=database,
|
||||
entered=entered, release=release, calls=calls,
|
||||
)
|
||||
finally:
|
||||
release.set()
|
||||
if future is not None:
|
||||
future.result(timeout=1)
|
||||
|
||||
|
||||
def _manager() -> PluginManager:
|
||||
"""
|
||||
仅装配停机与准入所需字段,避免触碰单例和真实插件持久化服务。
|
||||
"""
|
||||
manager = object.__new__(PluginManager)
|
||||
manager._plugin_quiesce_lock = threading.RLock()
|
||||
manager._plugin_quiesce_future = None
|
||||
manager._plugin_service_quiesce_future = None
|
||||
manager._plugin_runtime_closed = False
|
||||
manager._plugin_mutation_admission = PluginMutationAdmission(
|
||||
activity=lambda: manager._plugin_lifecycle.activity(),
|
||||
)
|
||||
return manager
|
||||
|
||||
|
||||
def test_slow_hook_rejects_other_lifecycle_without_waiting() -> None:
|
||||
"""
|
||||
A 的钩子未退出时,B 必须明确拒绝执行且不能等到 A 释放。
|
||||
"""
|
||||
with _blocked_plugin() as blocked:
|
||||
contender = blocked.executor.submit(blocked.lifecycle.start, "OtherPlugin")
|
||||
with pytest.raises(PluginMutationRejectedError, match="SlowPlugin.*close"):
|
||||
# 旧实现会在全局锁内等到此 Future 超时,因而使本断言失败。
|
||||
try:
|
||||
contender.result(timeout=0.3)
|
||||
except FutureTimeoutError:
|
||||
pytest.fail("慢钩子使其他插件的生命周期操作一直等待全局锁")
|
||||
assert blocked.running["SlowPlugin"] is blocked.instance
|
||||
blocked.database.release.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_shutdown_budget_includes_contended_lifecycle_and_keeps_loop_alive(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
停机预算包含准入等待,事件循环可继续调度且资源不能提前释放。
|
||||
"""
|
||||
manager = _manager()
|
||||
with _blocked_plugin(manager) as blocked:
|
||||
monkeypatch.setattr(
|
||||
"app.runtime.extensions.plugin.manager.ThreadHelper",
|
||||
lambda: SimpleNamespace(submit=blocked.executor.submit),
|
||||
)
|
||||
|
||||
heartbeat = asyncio.Event()
|
||||
asyncio.get_running_loop().call_later(0.01, heartbeat.set)
|
||||
started = time.monotonic()
|
||||
result = await manager.quiesce_plugins(timeout=0.05)
|
||||
assert time.monotonic() - started < 0.5
|
||||
assert result is False
|
||||
assert heartbeat.is_set()
|
||||
assert blocked.running["SlowPlugin"] is blocked.instance
|
||||
assert manager.finalize_plugins() is False
|
||||
blocked.database.release.assert_not_called()
|
||||
assert blocked.future.done() is False
|
||||
|
||||
|
||||
def test_busy_mutation_rejects_before_side_effects_and_preserves_owner() -> None:
|
||||
"""
|
||||
根事务在写入前快速拒绝,副作用、owner 和数据库均保持真实状态。
|
||||
"""
|
||||
manager = _manager()
|
||||
changed = []
|
||||
with _blocked_plugin(manager) as blocked:
|
||||
with pytest.raises(PluginMutationRejectedError, match="SlowPlugin.*close"):
|
||||
with manager.mutation("保存 OtherPlugin 配置"):
|
||||
changed.append(True)
|
||||
assert changed == []
|
||||
assert manager._plugin_mutation_admission.active_count == 1
|
||||
assert manager._plugin_mutation_admission.wait_until_idle(timeout=0.01) is False
|
||||
activity = manager.get_plugin_lifecycle_activity()
|
||||
assert activity.plugin_id == "SlowPlugin"
|
||||
assert activity.hook == "close"
|
||||
assert activity.elapsed_seconds >= activity.hook_elapsed_seconds > 0
|
||||
assert blocked.future.done() is False
|
||||
assert manager._plugin_mutation_admission.wait_until_idle(timeout=0) is True
|
||||
assert manager.get_plugin_lifecycle_activity() is None
|
||||
with manager.mutation("重试保存 OtherPlugin 配置"):
|
||||
changed.append(True)
|
||||
assert changed == [True]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_shutdown_keeps_real_hook_owner_and_reuses_future(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
调用方取消或再次超时都不能重复执行钩子、释放实例或销毁数据库。
|
||||
"""
|
||||
manager = _manager()
|
||||
with _blocked_plugin(manager, start=False) as blocked:
|
||||
monkeypatch.setattr(
|
||||
"app.runtime.extensions.plugin.manager.ThreadHelper",
|
||||
lambda: SimpleNamespace(submit=blocked.executor.submit),
|
||||
)
|
||||
assert await manager.quiesce_plugins(timeout=1) is True
|
||||
task = asyncio.create_task(manager.quiesce_plugin_services(timeout=1))
|
||||
try:
|
||||
assert await asyncio.to_thread(blocked.entered.wait, 1)
|
||||
owner = manager._plugin_service_quiesce_future
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert owner is not None and not owner.done()
|
||||
assert await manager.quiesce_plugin_services(timeout=0.01) is False
|
||||
assert manager._plugin_service_quiesce_future is owner
|
||||
assert blocked.calls == ["close"]
|
||||
assert manager.finalize_plugins() is False
|
||||
assert manager.reopen_plugins() is False
|
||||
assert blocked.running["SlowPlugin"] is blocked.instance
|
||||
blocked.database.release.assert_not_called()
|
||||
activity = manager.get_plugin_lifecycle_activity()
|
||||
assert activity.operation == "quiesce_services"
|
||||
assert activity.plugin_id == "SlowPlugin"
|
||||
assert activity.hook == "close"
|
||||
blocked.release.set()
|
||||
assert await asyncio.wrap_future(owner) is True
|
||||
assert manager.finalize_plugins() is True
|
||||
assert blocked.running == {}
|
||||
blocked.database.release.assert_called_once_with("SlowPlugin")
|
||||
finally:
|
||||
blocked.release.set()
|
||||
if not task.done():
|
||||
await task
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_summary_exposes_real_hook_and_does_not_report_ready(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
摘要在后台收敛标记为空闲时,仍能识别实际执行中的插件钩子。
|
||||
"""
|
||||
from app.api.endpoints import plugin as endpoint
|
||||
from app.schemas.plugin import PluginRuntimeStatus
|
||||
|
||||
with _blocked_plugin() as blocked:
|
||||
manager = SimpleNamespace(
|
||||
get_plugin_runtime_statuses=lambda: {"SlowPlugin": PluginRuntimeStatus.READY},
|
||||
get_plugin_restart_requirements=lambda: {},
|
||||
get_plugin_gil_fallbacks=lambda: [],
|
||||
get_plugin_runtime_generation=lambda: 3,
|
||||
is_plugin_settling=lambda: False,
|
||||
get_plugin_lifecycle_activity=blocked.lifecycle.activity,
|
||||
)
|
||||
monkeypatch.setattr(endpoint, "get_plugin_manager", lambda: manager)
|
||||
monkeypatch.setattr(
|
||||
endpoint, "get_configured_system_config",
|
||||
lambda: SimpleNamespace(get=lambda _key: ["SlowPlugin"]),
|
||||
)
|
||||
summary = await endpoint.runtime_status(None)
|
||||
assert summary.ready is False
|
||||
assert summary.pending_count == 1
|
||||
assert summary.active_operation.plugin_id == "SlowPlugin"
|
||||
assert summary.active_operation.hook == "close"
|
||||
assert summary.model_dump()["active_operation"]["elapsed_seconds"] >= 0
|
||||
summary = await endpoint.runtime_status(None)
|
||||
assert summary.ready is True
|
||||
assert summary.active_operation is None
|
||||
@@ -5,11 +5,12 @@
|
||||
import threading
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from app.runtime.extensions.plugin.lifecycle import PluginLifecycle
|
||||
import pytest
|
||||
|
||||
# 停止一侧在停机 hook 里等待加载一侧的预算。start 不持锁时加载会立刻完成并置位,
|
||||
# 等待即刻返回;start 持锁时加载被挡在锁外,这里必然等满。两种实现下交错顺序都是
|
||||
# 确定的,用例不依赖线程被调度的先后。
|
||||
from app.runtime.extensions.plugin.lifecycle import PluginLifecycle
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
|
||||
# 停止一侧在停机 hook 里等待加载一侧的预算;竞争加载必须先拒绝,停机后才允许重试。
|
||||
_INTERLEAVE_BUDGET = 0.3
|
||||
# 线程握手与回收的宽松预算,仅用于避免实现回归时把整个测试进程挂死
|
||||
_HANDSHAKE_BUDGET = 5.0
|
||||
@@ -120,7 +121,8 @@ def test_concurrent_start_does_not_orphan_the_instance_it_loads() -> None:
|
||||
等停止进入停机 hook 之后再发起加载,制造确定的交错顺序。
|
||||
"""
|
||||
assert quiesce_entered.wait(_HANDSHAKE_BUDGET)
|
||||
lifecycle.start("DemoPlugin")
|
||||
with pytest.raises(PluginMutationRejectedError):
|
||||
lifecycle.start("DemoPlugin")
|
||||
start_finished.set()
|
||||
|
||||
loader = threading.Thread(target=load, name="plugin-start", daemon=True)
|
||||
@@ -132,6 +134,9 @@ def test_concurrent_start_does_not_orphan_the_instance_it_loads() -> None:
|
||||
|
||||
assert not loader.is_alive()
|
||||
assert stopped == [seed]
|
||||
assert constructed == []
|
||||
# 明确拒绝没有执行副作用,原 owner 完成后可安全重试,并继续验证实例不会遗失。
|
||||
lifecycle.start("DemoPlugin")
|
||||
assert len(constructed) == 1
|
||||
orphaned = [
|
||||
instance
|
||||
|
||||
@@ -6,10 +6,12 @@ import asyncio
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import suppress
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.plugin.lifecycle import PluginLifecycleCoordinator
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
|
||||
|
||||
async def _assert_event_waits(event: asyncio.Event) -> None:
|
||||
@@ -168,7 +170,13 @@ async def test_startup_token_can_cross_threads_without_contextvar() -> None:
|
||||
main_thread = threading.current_thread().name
|
||||
|
||||
def run_in_thread(startup_token: object) -> tuple[str, set[str]]:
|
||||
"""
|
||||
在独立事件循环中验证启动令牌的显式跨线程授权。
|
||||
"""
|
||||
async def hold_plugin() -> tuple[str, set[str]]:
|
||||
"""
|
||||
在工作线程内取得逐插件资格并返回持有事实。
|
||||
"""
|
||||
async with coordinator.hold("DemoPlugin", startup_token):
|
||||
return threading.current_thread().name, set(coordinator._active_plugins)
|
||||
|
||||
@@ -203,3 +211,48 @@ async def test_hold_without_token_retains_startup_waiting_compatibility() -> Non
|
||||
task = asyncio.create_task(external_hold())
|
||||
await _assert_event_waits(entered)
|
||||
await _cancel_task(task)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admission_deadline_does_not_release_plugin_or_startup_owner() -> None:
|
||||
"""
|
||||
等待预算耗尽后现有租约仍有效,后续请求不能越权进入。
|
||||
"""
|
||||
coordinator = PluginLifecycleCoordinator()
|
||||
async with coordinator.hold("SlowPlugin"):
|
||||
with pytest.raises(PluginMutationRejectedError, match="slowplugin.*秒"):
|
||||
async with coordinator.hold("SLOWPLUGIN", timeout=0.01):
|
||||
pytest.fail("重复插件资格被放行")
|
||||
with pytest.raises(PluginMutationRejectedError, match="slowplugin"):
|
||||
async with coordinator.hold_startup(timeout=0.01):
|
||||
pytest.fail("启动资格被错误放行")
|
||||
assert coordinator._active_plugins == {"slowplugin"}
|
||||
async with coordinator.hold("OtherPlugin", timeout=0):
|
||||
assert coordinator._active_plugins == {"slowplugin", "otherplugin"}
|
||||
async with coordinator.hold_startup() as token:
|
||||
with pytest.raises(PluginMutationRejectedError, match="启动同步"):
|
||||
async with coordinator.hold("OtherPlugin", timeout=0):
|
||||
pytest.fail("外部请求穿过启动屏障")
|
||||
assert coordinator._startup_token is token
|
||||
async with coordinator.hold("SlowPlugin", timeout=0):
|
||||
assert coordinator._active_plugins == {"slowplugin"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("startup", [False, True])
|
||||
async def test_admission_does_not_acquire_after_wait_budget_expires(
|
||||
startup: bool, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
即使持有者在等待预算耗尽时释放,也不能在截止时间之后取得新资格。
|
||||
"""
|
||||
coordinator = PluginLifecycleCoordinator()
|
||||
acquire = Mock(side_effect=[None, object()] if startup else [False, True])
|
||||
monkeypatch.setattr(
|
||||
coordinator, "_try_acquire_startup" if startup else "_try_acquire_plugin", acquire,
|
||||
)
|
||||
lease = coordinator.hold_startup(timeout=0.01) if startup else coordinator.hold("DemoPlugin", timeout=0.01)
|
||||
with pytest.raises(PluginMutationRejectedError, match="准入正忙"):
|
||||
async with lease:
|
||||
pytest.fail("预算耗尽后仍然取得执行权")
|
||||
acquire.assert_called_once()
|
||||
|
||||
@@ -196,18 +196,21 @@ async def test_quiesce_timeout_retains_admitted_owner_and_nested_reload(
|
||||
await entered.wait()
|
||||
|
||||
assert await manager.quiesce_plugins(timeout=0.01) is False
|
||||
owner = manager._plugin_quiesce_future
|
||||
assert owner is not None
|
||||
assert owner.done() is False
|
||||
waiter = manager._plugin_quiesce_future
|
||||
assert manager._plugin_mutation_admission.active_count == 1
|
||||
assert manager.finalize_plugins() is False
|
||||
with pytest.raises(PluginMutationRejectedError):
|
||||
with manager.mutation("新的配置写入"):
|
||||
pass
|
||||
|
||||
if waiter is not None:
|
||||
# 等待者可以按预算退出,真实变更仍由 admission 持有;再次停机才关闭 handler。
|
||||
assert await asyncio.wrap_future(waiter) is False
|
||||
assert manager._plugin_mutation_admission.active_count == 1
|
||||
manager._plugin_lifecycle.quiesce_handlers.assert_not_called()
|
||||
release.set()
|
||||
assert await mutation_task is PluginRuntimeStatus.ACTIVE
|
||||
assert await asyncio.wrap_future(owner) is True
|
||||
assert await manager.quiesce_plugins(timeout=1) is True
|
||||
|
||||
manager._plugin_lifecycle.reload.assert_called_once_with(
|
||||
"DemoPlugin",
|
||||
|
||||
Reference in New Issue
Block a user