mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-25 05:12:42 +08:00
refactor(plugin): converge runtime ownership and compatibility
This commit is contained in:
3637
app/adapters/external/market.py
vendored
3637
app/adapters/external/market.py
vendored
File diff suppressed because it is too large
Load Diff
1534
app/adapters/external/plugin/client.py
vendored
1534
app/adapters/external/plugin/client.py
vendored
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@ from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from importlib.metadata import PackageNotFoundError, distribution, distributions
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Optional, Protocol
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from packaging.markers import default_environment
|
||||
@@ -16,6 +16,7 @@ from packaging.requirements import Requirement
|
||||
from packaging.specifiers import InvalidSpecifier, SpecifierSet
|
||||
from packaging.version import InvalidVersion, Version
|
||||
|
||||
from app.adapters.system.plugin.health import PluginRuntimeHealth
|
||||
from app.adapters.system.plugin.manifest import (
|
||||
PluginDependencyManifestError,
|
||||
load_dependency_manifest,
|
||||
@@ -34,22 +35,38 @@ class _RequirementGroup:
|
||||
specifiers: set[str] = field(default_factory=set) # 待求交集的版本约束
|
||||
|
||||
|
||||
class PluginDependencyPackagePort(Protocol):
|
||||
"""声明依赖聚合器所需的唯一 Python 包安装边界。"""
|
||||
|
||||
def install_packages_with_fallback(
|
||||
self,
|
||||
dependency_files: list[Path],
|
||||
find_links_dirs: list[Path],
|
||||
) -> tuple[bool, str]:
|
||||
"""同步安装已经聚合并准入的依赖清单。"""
|
||||
|
||||
async def async_install_packages_with_fallback(
|
||||
self,
|
||||
dependency_files: list[Path],
|
||||
find_links_dirs: list[Path],
|
||||
) -> tuple[bool, str]:
|
||||
"""异步安装已经聚合并准入的依赖清单。"""
|
||||
|
||||
|
||||
class PluginDependencyInstaller:
|
||||
"""独立负责插件依赖扫描、约束合并和安装。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
helper: Any = None,
|
||||
packages: Optional[PluginDependencyPackagePort] = None,
|
||||
*,
|
||||
installed_plugins_provider: Optional[Callable[[], list[str]]] = None,
|
||||
plugin_dir: Optional[Path] = None,
|
||||
) -> None:
|
||||
"""保存包安装端口和启动层提供的已安装插件读取器。"""
|
||||
if helper is None:
|
||||
from app.adapters.external.market import PluginHelper
|
||||
|
||||
helper = PluginHelper()
|
||||
self._helper = helper
|
||||
if packages is None:
|
||||
packages = PluginRuntimeHealth()
|
||||
self._packages = packages
|
||||
self._installed_plugins_provider = installed_plugins_provider or (lambda: [])
|
||||
self._plugin_dir = plugin_dir or (
|
||||
Path(get_runtime_setting('ROOT_PATH')) / "app" / "plugins"
|
||||
@@ -178,7 +195,7 @@ class PluginDependencyInstaller:
|
||||
requirement.marker.evaluate({**environment, "extra": extra})
|
||||
for extra in extras
|
||||
)
|
||||
return requirement.marker.evaluate(environment)
|
||||
return bool(requirement.marker.evaluate(environment))
|
||||
|
||||
@staticmethod
|
||||
def _standardize_extra(name: str) -> str:
|
||||
@@ -351,7 +368,7 @@ class PluginDependencyInstaller:
|
||||
manifest_paths = [manifest.path for manifest in self._plugin_manifests()]
|
||||
if not manifest_paths:
|
||||
return False, "没有找到已安装插件的依赖清单"
|
||||
return self._helper.install_packages_with_fallback(
|
||||
return self._packages.install_packages_with_fallback(
|
||||
manifest_paths,
|
||||
self._wheels_dirs(),
|
||||
)
|
||||
@@ -371,7 +388,7 @@ class PluginDependencyInstaller:
|
||||
manifest_paths = [manifest.path for manifest in self._plugin_manifests()]
|
||||
if not manifest_paths:
|
||||
return False, "没有找到已安装插件的依赖清单"
|
||||
return await self._helper.async_install_packages_with_fallback(
|
||||
return await self._packages.async_install_packages_with_fallback(
|
||||
manifest_paths,
|
||||
self._wheels_dirs(),
|
||||
)
|
||||
|
||||
1060
app/adapters/system/plugin/health.py
Normal file
1060
app/adapters/system/plugin/health.py
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,12 @@
|
||||
"""插件 Agent 工具共享辅助方法"""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.adapters.external.market import PluginHelper
|
||||
from app.adapters.external.plugin.client import is_local_repo_url
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.plugin.gateway import get_plugin_install_service
|
||||
from app.application.plugin.runtime import get_plugin_manager
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.plugin import PluginRuntimeStatus
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
@@ -23,17 +20,6 @@ DEFAULT_PLUGIN_CANDIDATE_LIMIT = 50
|
||||
MAX_PLUGIN_CANDIDATE_LIMIT = 200
|
||||
|
||||
|
||||
def _remove_plugin_directory(path: Path) -> bool:
|
||||
"""删除插件目录并返回是否完成,供受控线程执行。"""
|
||||
if not path.exists():
|
||||
return False
|
||||
try:
|
||||
shutil.rmtree(path)
|
||||
except Exception:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def get_plugin_snapshot(plugin_id: str) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
获取已安装插件的基础信息快照。
|
||||
@@ -118,7 +104,7 @@ def summarize_plugin(plugin: Any) -> dict[str, Any]:
|
||||
"system_version_message": getattr(plugin, "system_version_message", None),
|
||||
"state": bool(getattr(plugin, "state", False)),
|
||||
"repo_url": repo_url,
|
||||
"source": "local_repo" if PluginHelper.is_local_repo_url(repo_url) else "market",
|
||||
"source": "local_repo" if is_local_repo_url(repo_url) else "market",
|
||||
}
|
||||
|
||||
|
||||
@@ -394,12 +380,11 @@ async def uninstall_plugin_runtime(plugin_id: str) -> dict[str, Any]:
|
||||
elif was_clone:
|
||||
plugin_manager.delete_plugin_config(plugin_id)
|
||||
plugin_manager.delete_plugin_data(plugin_id)
|
||||
plugin_base_dir = get_runtime_setting('ROOT_PATH') / "app" / "plugins" / plugin_id.lower()
|
||||
try:
|
||||
clone_files_removed = await run_agent_blocking(
|
||||
"plugin",
|
||||
_remove_plugin_directory,
|
||||
plugin_base_dir,
|
||||
plugin_manager.remove_plugin_package,
|
||||
plugin_id,
|
||||
)
|
||||
if clone_files_removed:
|
||||
plugin_manager.plugins.pop(plugin_id, None)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import mimetypes
|
||||
import shutil
|
||||
from typing import Annotated, Any, Dict, List, Optional
|
||||
|
||||
import aiofiles
|
||||
@@ -972,21 +971,9 @@ def uninstall_plugin(
|
||||
# 如果是分身插件,则删除分身数据和配置
|
||||
plugin_manager.delete_plugin_config(plugin_id)
|
||||
plugin_manager.delete_plugin_data(plugin_id)
|
||||
# 删除分身文件
|
||||
plugin_base_dir = (
|
||||
get_api_runtime_config_snapshot().root_path
|
||||
/ "app"
|
||||
/ "plugins"
|
||||
/ plugin_id.lower()
|
||||
)
|
||||
if plugin_base_dir.exists():
|
||||
try:
|
||||
shutil.rmtree(plugin_base_dir)
|
||||
plugin_manager.plugins.pop(plugin_id, None)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"删除插件分身目录 {plugin_base_dir} 失败: {str(e)}"
|
||||
)
|
||||
# 分身物理目录只能由包文件 owner 删除。
|
||||
if plugin_manager.remove_plugin_package(plugin_id):
|
||||
plugin_manager.plugins.pop(plugin_id, None)
|
||||
# 从插件文件夹中移除该插件
|
||||
remove_plugin_from_folders(plugin_id)
|
||||
# 移除插件
|
||||
|
||||
@@ -16,7 +16,7 @@ from anyio import Path as AsyncPath
|
||||
from fastapi import Body, Depends, Header, HTTPException, Request, Response
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from app.adapters.external.market import (
|
||||
from app.adapters.external.plugin.client import (
|
||||
PLUGIN_MARKET_WIKI_URL,
|
||||
extract_plugin_market_repos_from_wiki,
|
||||
merge_plugin_market_repos,
|
||||
|
||||
@@ -18,9 +18,9 @@ from app.application.plugin.source import (
|
||||
CandidateInventory,
|
||||
PluginLocalCandidate,
|
||||
PluginSelectionStatus,
|
||||
parse_local_plugin_reference,
|
||||
select_plugin_candidate,
|
||||
)
|
||||
from app.domain.plugin import parse_local_plugin_reference
|
||||
|
||||
|
||||
class PluginSourceAdmissionError(RuntimeError):
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.application.plugin.source import (
|
||||
PluginMarketCandidate,
|
||||
normalize_package_generation,
|
||||
)
|
||||
from app.domain.plugin import is_plugin_generation_compatible
|
||||
from app.foundation.environment import is_free_threaded_runtime
|
||||
|
||||
PLUGIN_V3_GENERATIONS = ("v3", "v2", "v1")
|
||||
@@ -353,7 +354,12 @@ def _market_candidates(
|
||||
plugin_id = raw_info.get("id") or index_plugin_id
|
||||
if not isinstance(plugin_id, str):
|
||||
continue
|
||||
if not _is_v3_compatible(raw_info, package_generation):
|
||||
if not is_plugin_generation_compatible(
|
||||
dict(raw_info),
|
||||
None if package_generation == "v1" else package_generation,
|
||||
current_generation="v3",
|
||||
free_threaded=is_free_threaded_runtime(),
|
||||
):
|
||||
continue
|
||||
plugin_version = raw_info.get("version")
|
||||
if plugin_version is None:
|
||||
@@ -377,20 +383,6 @@ def _market_candidates(
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _is_v3_compatible(
|
||||
plugin_info: Mapping[str, Any],
|
||||
package_generation: str,
|
||||
) -> bool:
|
||||
"""按宿主 V3、兼容 V2、基础索引顺序判断候选兼容性。"""
|
||||
if plugin_info.get("v3") is False:
|
||||
return False
|
||||
if is_free_threaded_runtime() and plugin_info.get("v3t") is False:
|
||||
return False
|
||||
if package_generation in {"v3", "v2"}:
|
||||
return True
|
||||
return plugin_info.get("v3") is True or plugin_info.get("v2") is True
|
||||
|
||||
|
||||
def _local_candidate(
|
||||
plugin_id: str,
|
||||
plugin_info: Mapping[str, Any],
|
||||
@@ -403,7 +395,12 @@ def _local_candidate(
|
||||
or "v1"
|
||||
)
|
||||
)
|
||||
if not _is_v3_compatible(plugin_info, generation):
|
||||
if not is_plugin_generation_compatible(
|
||||
dict(plugin_info),
|
||||
None if generation == "v1" else generation,
|
||||
current_generation="v3",
|
||||
free_threaded=is_free_threaded_runtime(),
|
||||
):
|
||||
return None
|
||||
repo_url = plugin_info.get("repo_url")
|
||||
if not isinstance(repo_url, str) or not repo_url.startswith("local://"):
|
||||
|
||||
@@ -6,7 +6,6 @@ from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from enum import StrEnum
|
||||
from typing import Any, TypeAlias
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
from app.application.plugin.identity import (
|
||||
PluginIdentity,
|
||||
@@ -825,18 +824,6 @@ def get_effective_local_candidate(
|
||||
return candidate if isinstance(candidate, PluginLocalCandidate) else None
|
||||
|
||||
|
||||
def parse_local_plugin_reference(repo_url: str) -> str | None:
|
||||
"""从不透明本地来源标识中提取插件 ID,不读取或暴露宿主路径。"""
|
||||
if not str(repo_url).startswith("local://"):
|
||||
return None
|
||||
try:
|
||||
parsed = urlsplit(repo_url)
|
||||
plugin_id = unquote(parsed.netloc or parsed.path.strip("/"))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return plugin_id or None
|
||||
|
||||
|
||||
def _coerce_online_source_type(source_type: TrustedPluginSourceType) -> TrustedPluginSourceType:
|
||||
"""把外部字符串来源类型转换为可信在线来源枚举。"""
|
||||
value = TrustedPluginSourceType(source_type)
|
||||
|
||||
228
app/domain/plugin.py
Normal file
228
app/domain/plugin.py
Normal file
@@ -0,0 +1,228 @@
|
||||
"""插件来源、代际与安装计划的纯领域规则。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs, quote, unquote, urlsplit
|
||||
|
||||
from packaging.specifiers import InvalidSpecifier, SpecifierSet
|
||||
from packaging.version import InvalidVersion, Version
|
||||
|
||||
LOCAL_PLUGIN_SOURCE_PREFIX = "local://"
|
||||
PLUGIN_SYSTEM_VERSION_FIELD = "system_version"
|
||||
PLUGIN_GENERATION_COMPATIBILITY: dict[str, tuple[str, ...]] = {
|
||||
"v3": ("v2",),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PluginReleaseInstallPlan:
|
||||
"""描述远端插件内容准备模式,不持有同步或异步 I/O 实现。"""
|
||||
|
||||
release_tag: str | None
|
||||
fallback_to_filelist: bool
|
||||
|
||||
|
||||
def is_local_plugin_source(repo_url: str | None) -> bool:
|
||||
"""判断插件来源是否为宿主定义的不透明本地仓库标识。"""
|
||||
return bool(repo_url and repo_url.startswith(LOCAL_PLUGIN_SOURCE_PREFIX))
|
||||
|
||||
|
||||
def build_local_plugin_source(
|
||||
plugin_id: str,
|
||||
*,
|
||||
repo_path: str | None = None,
|
||||
package_generation: str | None = None,
|
||||
) -> str:
|
||||
"""生成本地插件来源标识,不解释或访问其中的宿主路径。"""
|
||||
repo_url = f"{LOCAL_PLUGIN_SOURCE_PREFIX}{quote(plugin_id, safe='')}"
|
||||
parameters: list[str] = []
|
||||
if repo_path:
|
||||
parameters.append(f"path={quote(repo_path, safe='/:~')}")
|
||||
if package_generation:
|
||||
parameters.append(f"version={quote(package_generation, safe='')}")
|
||||
return f"{repo_url}?{'&'.join(parameters)}" if parameters else repo_url
|
||||
|
||||
|
||||
def parse_local_plugin_reference(repo_url: str) -> str | None:
|
||||
"""从不透明本地来源标识中提取插件 ID。"""
|
||||
if not is_local_plugin_source(repo_url):
|
||||
return None
|
||||
try:
|
||||
parsed = urlsplit(repo_url)
|
||||
plugin_id = unquote(parsed.netloc or parsed.path.strip("/"))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return plugin_id or None
|
||||
|
||||
|
||||
def parse_local_plugin_path(repo_url: str) -> str | None:
|
||||
"""从本地来源标识中提取未解释的仓库路径字符串。"""
|
||||
if not is_local_plugin_source(repo_url):
|
||||
return None
|
||||
try:
|
||||
values = parse_qs(urlsplit(repo_url).query).get("path")
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
def parse_local_plugin_generation(repo_url: str) -> str | None:
|
||||
"""从本地来源标识中提取 package 代际。"""
|
||||
if not is_local_plugin_source(repo_url):
|
||||
return None
|
||||
try:
|
||||
values = parse_qs(urlsplit(repo_url).query).get("version")
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
def compatible_plugin_generations(current_generation: str | None) -> tuple[str, ...]:
|
||||
"""返回当前宿主允许读取的插件代际,按优先级去重。"""
|
||||
if not current_generation:
|
||||
return ()
|
||||
return tuple(
|
||||
dict.fromkeys(
|
||||
(
|
||||
current_generation,
|
||||
*PLUGIN_GENERATION_COMPATIBILITY.get(current_generation, ()),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def plugin_generation_candidates(
|
||||
requested_generation: str | None,
|
||||
*,
|
||||
current_generation: str | None,
|
||||
) -> tuple[str, ...]:
|
||||
"""返回安装读取唯一的代际候选顺序,并把基础索引固定在末尾。"""
|
||||
preferred_generation = requested_generation or current_generation
|
||||
candidates = [preferred_generation]
|
||||
candidates.extend(
|
||||
PLUGIN_GENERATION_COMPATIBILITY.get(preferred_generation or "", ())
|
||||
)
|
||||
candidates.append("")
|
||||
return tuple(dict.fromkeys(candidate or "" for candidate in candidates))
|
||||
|
||||
|
||||
def is_plugin_generation_compatible(
|
||||
plugin_info: object,
|
||||
package_generation: str | None,
|
||||
*,
|
||||
current_generation: str | None,
|
||||
free_threaded: bool,
|
||||
) -> bool:
|
||||
"""按当前代际、兼容代际和基础索引规则判断一个市场条目。"""
|
||||
if not isinstance(plugin_info, Mapping):
|
||||
return False
|
||||
if free_threaded and plugin_info.get("v3t") is False:
|
||||
return False
|
||||
if not current_generation:
|
||||
return not package_generation
|
||||
if plugin_info.get(current_generation) is False:
|
||||
return False
|
||||
if package_generation == current_generation:
|
||||
return True
|
||||
if package_generation in PLUGIN_GENERATION_COMPATIBILITY.get(
|
||||
current_generation, ()
|
||||
):
|
||||
return plugin_info.get(current_generation) is not False
|
||||
if package_generation:
|
||||
return False
|
||||
if plugin_info.get(current_generation) is True:
|
||||
return True
|
||||
return any(
|
||||
plugin_info.get(generation) is True
|
||||
for generation in PLUGIN_GENERATION_COMPATIBILITY.get(
|
||||
current_generation, ()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def check_plugin_system_version(
|
||||
plugin_info: object,
|
||||
*,
|
||||
current_version: str,
|
||||
) -> tuple[bool, str]:
|
||||
"""检查插件声明的 MoviePilot PEP 440 版本范围。"""
|
||||
if not isinstance(plugin_info, Mapping):
|
||||
return True, ""
|
||||
raw_specifier = plugin_info.get(PLUGIN_SYSTEM_VERSION_FIELD)
|
||||
if raw_specifier is None or raw_specifier == "":
|
||||
return True, ""
|
||||
if not isinstance(raw_specifier, str):
|
||||
return False, (
|
||||
f"插件限定的系统版本范围 {PLUGIN_SYSTEM_VERSION_FIELD} 必须是字符串,"
|
||||
f"请使用 PEP 440 版本范围格式,例如 >=2.12.0,<3"
|
||||
)
|
||||
try:
|
||||
system_version = Version(current_version)
|
||||
except InvalidVersion:
|
||||
return False, (
|
||||
f"当前 MoviePilot 版本 {current_version} 无法解析,"
|
||||
f"已拒绝安装带版本限制的插件"
|
||||
)
|
||||
try:
|
||||
specifier_set = SpecifierSet(raw_specifier)
|
||||
except InvalidSpecifier:
|
||||
return False, (
|
||||
f"插件限定的系统版本范围格式不正确:{raw_specifier},"
|
||||
f"请使用 PEP 440 版本范围格式,例如 >=2.12.0,<3"
|
||||
)
|
||||
if specifier_set.contains(system_version, prereleases=True):
|
||||
return True, ""
|
||||
return False, (
|
||||
f"插件要求 MoviePilot 版本 {raw_specifier},当前版本 {current_version} 不满足,"
|
||||
f"已拒绝安装"
|
||||
)
|
||||
|
||||
|
||||
def build_plugin_release_install_plan(
|
||||
*,
|
||||
plugin_id: str,
|
||||
metadata: Mapping[str, Any],
|
||||
release_version: str | None,
|
||||
release_items: Sequence[Mapping[str, Any]],
|
||||
current_version: str,
|
||||
) -> tuple[PluginReleaseInstallPlan | None, str]:
|
||||
"""统一选择指定 Release、可回退当前 Release 或文件列表安装模式。"""
|
||||
is_release = metadata.get("release")
|
||||
plugin_version = metadata.get("version")
|
||||
if release_version:
|
||||
if not is_release:
|
||||
return None, f"{plugin_id} 未声明 Release 安装,无法安装指定版本"
|
||||
if not any(
|
||||
item.get("version") == release_version for item in release_items
|
||||
):
|
||||
return None, f"{plugin_id} 未找到可安装的 Release 版本:{release_version}"
|
||||
if release_version == plugin_version:
|
||||
compatible, message = check_plugin_system_version(
|
||||
metadata,
|
||||
current_version=current_version,
|
||||
)
|
||||
if not compatible:
|
||||
return None, message
|
||||
return PluginReleaseInstallPlan(
|
||||
release_tag=f"{plugin_id}_v{release_version}",
|
||||
fallback_to_filelist=False,
|
||||
), ""
|
||||
compatible, message = check_plugin_system_version(
|
||||
metadata,
|
||||
current_version=current_version,
|
||||
)
|
||||
if not compatible:
|
||||
return None, message
|
||||
if not is_release:
|
||||
return PluginReleaseInstallPlan(None, False), ""
|
||||
if not plugin_version:
|
||||
return None, (
|
||||
f"未在插件清单中找到 {plugin_id} 的版本号,无法进行 Release 安装"
|
||||
)
|
||||
return PluginReleaseInstallPlan(
|
||||
release_tag=f"{plugin_id}_v{plugin_version}",
|
||||
fallback_to_filelist=True,
|
||||
), ""
|
||||
@@ -3,9 +3,11 @@
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.runtime.extensions.plugin.registry import PluginRegistry
|
||||
from app.runtime.extensions.plugin.system import PluginSystemServices
|
||||
from app.schemas.plugin import PluginInstance, PluginRuntimeStatus
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -32,10 +34,14 @@ class PluginDependencyService:
|
||||
self,
|
||||
*,
|
||||
system: Callable[[], PluginSystemServices],
|
||||
instances: Optional[Callable[[], dict[str, PluginInstance]]] = None,
|
||||
registry: Optional[PluginRegistry] = None,
|
||||
log: Any,
|
||||
) -> None:
|
||||
"""保存插件系统适配器和日志端口。"""
|
||||
"""保存插件系统、虚拟实例和运行状态端口。"""
|
||||
self._system = system
|
||||
self._instances = instances or (lambda: {})
|
||||
self._registry = registry
|
||||
self._logger = log
|
||||
|
||||
def install_missing_with_status(self) -> PluginDependencyInstallResult:
|
||||
@@ -85,12 +91,54 @@ class PluginDependencyService:
|
||||
return PluginDependencyInstallResult(missing=missing, success=success)
|
||||
|
||||
def classify_plugins(self) -> PluginDependencyClassification:
|
||||
"""返回启动编排使用的轻量插件分类。"""
|
||||
"""分类物理插件,并把源码结论映射到全部虚拟实例。"""
|
||||
ready, missing_dependencies, missing_source = (
|
||||
self._system().dependency.classify_plugins()
|
||||
)
|
||||
ready = list(ready)
|
||||
missing_dependencies = list(missing_dependencies)
|
||||
missing_source = list(missing_source)
|
||||
source_ready = set(ready)
|
||||
source_pending = set(missing_dependencies)
|
||||
for instance in self._instances().values():
|
||||
if instance.source_plugin_id in source_ready:
|
||||
ready.append(instance.instance_id)
|
||||
elif instance.source_plugin_id in source_pending:
|
||||
missing_dependencies.append(instance.instance_id)
|
||||
else:
|
||||
missing_source.append(instance.instance_id)
|
||||
return PluginDependencyClassification(
|
||||
ready=tuple(ready),
|
||||
missing_dependencies=tuple(missing_dependencies),
|
||||
missing_source=tuple(missing_source),
|
||||
)
|
||||
|
||||
def apply_classification(
|
||||
self,
|
||||
classification: PluginDependencyClassification,
|
||||
) -> None:
|
||||
"""把依赖分类写入唯一注册表,已激活插件保持当前状态。"""
|
||||
if self._registry is None:
|
||||
raise RuntimeError("插件依赖状态注册表尚未装配")
|
||||
running_ids = set(self._registry.running_ids())
|
||||
for plugin_id in classification.missing_source:
|
||||
self._registry.set_runtime_status(
|
||||
plugin_id,
|
||||
PluginRuntimeStatus.SOURCE_MISSING,
|
||||
)
|
||||
for plugin_id in classification.missing_dependencies:
|
||||
self._registry.set_runtime_status(
|
||||
plugin_id,
|
||||
PluginRuntimeStatus.DEPENDENCY_PENDING,
|
||||
)
|
||||
for plugin_id in classification.ready:
|
||||
current_status = self._registry.runtime_status(plugin_id)
|
||||
if (
|
||||
plugin_id in running_ids
|
||||
and current_status is not PluginRuntimeStatus.DEPENDENCY_PENDING
|
||||
):
|
||||
continue
|
||||
self._registry.set_runtime_status(
|
||||
plugin_id,
|
||||
PluginRuntimeStatus.READY,
|
||||
)
|
||||
|
||||
324
app/runtime/extensions/plugin/runtime.py
Normal file
324
app/runtime/extensions/plugin/runtime.py
Normal file
@@ -0,0 +1,324 @@
|
||||
"""插件宿主运行时依赖聚合与构造。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional, Protocol
|
||||
|
||||
from app.foundation.crypto import RSAUtils
|
||||
from app.foundation.version import compare_version
|
||||
from app.runtime.events import eventmanager
|
||||
from app.runtime.extensions.plugin.access import PluginAccessPolicy
|
||||
from app.runtime.extensions.plugin.admission import PluginMutationAdmission
|
||||
from app.runtime.extensions.plugin.catalog import PluginCatalogFacade
|
||||
from app.runtime.extensions.plugin.clone import PluginCloneService
|
||||
from app.runtime.extensions.plugin.dependency import PluginDependencyService
|
||||
from app.runtime.extensions.plugin.lifecycle import PluginLifecycle
|
||||
from app.runtime.extensions.plugin.loader import PluginLoader
|
||||
from app.runtime.extensions.plugin.metadata import PluginMetadataMapper
|
||||
from app.runtime.extensions.plugin.monitor import PluginMonitorController
|
||||
from app.runtime.extensions.plugin.paths import PluginPathResolver
|
||||
from app.runtime.extensions.plugin.projection import PluginProjection
|
||||
from app.runtime.extensions.plugin.registry import PluginRegistry
|
||||
from app.runtime.extensions.plugin.storage import (
|
||||
PluginConfigStore,
|
||||
PluginInstanceStore,
|
||||
PluginStorage,
|
||||
)
|
||||
from app.runtime.extensions.plugin.sync import (
|
||||
LocalPluginSyncService,
|
||||
PluginSyncService,
|
||||
)
|
||||
from app.runtime.extensions.plugin.system import PluginSystemServices
|
||||
from app.runtime.extensions.plugin.tools import PluginToolCatalog
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class PluginRuntimeHost(Protocol):
|
||||
"""声明运行时 owner 回调宿主生命周期门面的最小合同。"""
|
||||
|
||||
def reload_plugin(self, plugin_id: str) -> Any:
|
||||
"""重载指定插件。"""
|
||||
...
|
||||
|
||||
def remove_plugin(self, plugin_id: str) -> Any:
|
||||
"""移除指定插件运行实例。"""
|
||||
...
|
||||
|
||||
@staticmethod
|
||||
def get_plugin_remote_entry(plugin_id: str, page: str) -> str:
|
||||
"""构造插件远程页面入口。"""
|
||||
...
|
||||
|
||||
def _run_file_watcher(self) -> None:
|
||||
"""运行插件文件监控循环。"""
|
||||
...
|
||||
|
||||
def get_plugins_from_market(
|
||||
self,
|
||||
market: str,
|
||||
package_version: Optional[str] = None,
|
||||
force: bool = False,
|
||||
) -> Optional[list[Any]]:
|
||||
"""读取指定市场目录。"""
|
||||
...
|
||||
|
||||
async def async_get_plugins_from_market(
|
||||
self,
|
||||
market: str,
|
||||
package_version: Optional[str] = None,
|
||||
force: bool = False,
|
||||
) -> Optional[list[Any]]:
|
||||
"""异步读取指定市场目录。"""
|
||||
...
|
||||
|
||||
|
||||
PluginCatalogFactory = Callable[[Callable[..., Any]], Any]
|
||||
PluginImportService = Callable[..., None]
|
||||
PluginRemoteEntryBuilder = Callable[[str, str], str]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PluginRuntimeEnvironment:
|
||||
"""保存由组合根提供的插件运行时外部端口。"""
|
||||
|
||||
plugins_root: Path
|
||||
storage: Callable[[], PluginStorage]
|
||||
system: Callable[[], PluginSystemServices]
|
||||
catalog_factory: PluginCatalogFactory
|
||||
import_preparer: PluginImportService
|
||||
import_scanner: PluginImportService
|
||||
auth_level: Callable[[], int]
|
||||
remote_entry: PluginRemoteEntryBuilder
|
||||
development: Callable[[], bool]
|
||||
logger: Any
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PluginRuntime:
|
||||
"""聚合一个 PluginManager 生命周期内唯一的职责 owner。"""
|
||||
|
||||
registry: PluginRegistry
|
||||
instances: PluginInstanceStore
|
||||
configs: PluginConfigStore
|
||||
access: PluginAccessPolicy
|
||||
catalog: PluginCatalogFacade
|
||||
paths: PluginPathResolver
|
||||
local_sync: LocalPluginSyncService
|
||||
monitor: PluginMonitorController
|
||||
admission: PluginMutationAdmission
|
||||
dependencies: PluginDependencyService
|
||||
loader: PluginLoader
|
||||
tools: PluginToolCatalog
|
||||
lifecycle: PluginLifecycle
|
||||
metadata: PluginMetadataMapper
|
||||
sync: PluginSyncService
|
||||
clone: PluginCloneService
|
||||
projection: PluginProjection
|
||||
recent_local_sync: dict[str, float]
|
||||
system: Callable[[], PluginSystemServices]
|
||||
|
||||
|
||||
def build_plugin_runtime(
|
||||
host: PluginRuntimeHost,
|
||||
environment: PluginRuntimeEnvironment,
|
||||
*,
|
||||
tool_build_max_attempts: int,
|
||||
) -> PluginRuntime:
|
||||
"""按依赖顺序构造唯一插件运行时,各业务能力仍由对应 owner 实现。"""
|
||||
registry = PluginRegistry()
|
||||
instances = PluginInstanceStore(storage=environment.storage)
|
||||
configs = PluginConfigStore(
|
||||
storage=environment.storage,
|
||||
plugin_exists=lambda plugin_id: bool(registry.classes.get(plugin_id)),
|
||||
)
|
||||
access = PluginAccessPolicy(
|
||||
auth_level=environment.auth_level,
|
||||
verify_keys=RSAUtils.verify_rsa_keys,
|
||||
log=environment.logger,
|
||||
)
|
||||
loader = PluginLoader(
|
||||
plugins_root=environment.plugins_root,
|
||||
import_preparer=environment.import_preparer,
|
||||
import_scanner=environment.import_scanner,
|
||||
log=environment.logger,
|
||||
)
|
||||
tools = PluginToolCatalog(max_attempts=tool_build_max_attempts)
|
||||
|
||||
def load_plugins(
|
||||
plugin_id: Optional[str],
|
||||
installed_plugins: list[str],
|
||||
validator: Callable[[Any], bool],
|
||||
) -> list[Any]:
|
||||
"""加载物理插件或虚拟实例,并保持持久化实例顺序。"""
|
||||
if plugin_id:
|
||||
instance = instances.get(plugin_id)
|
||||
if instance:
|
||||
return loader.load_instance(instance, validator)
|
||||
return loader.load(plugin_id, installed_plugins, validator)
|
||||
plugins = loader.load(None, installed_plugins, validator)
|
||||
for instance in instances.all().values():
|
||||
plugins.extend(loader.load_instance(instance, validator))
|
||||
return plugins
|
||||
|
||||
lifecycle = PluginLifecycle(
|
||||
classes=registry.classes,
|
||||
running=registry.running,
|
||||
load_plugins=load_plugins,
|
||||
installed_plugins=lambda: environment.storage().read(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
) or [],
|
||||
plugin_config=configs.read,
|
||||
auth_checker=lambda plugin: access.check(plugin),
|
||||
clear_modules=loader.clear_modules,
|
||||
clear_tools=tools.clear,
|
||||
enable_events=eventmanager.enable_event_handler,
|
||||
disable_events=eventmanager.disable_event_handler,
|
||||
runtime_status_writer=registry.set_runtime_status,
|
||||
log=environment.logger,
|
||||
event_sender=eventmanager.send_event,
|
||||
)
|
||||
metadata = PluginMetadataMapper(
|
||||
plugin_instance=registry.instance,
|
||||
plugin_class=registry.plugin_class,
|
||||
annotate_system_version=lambda info: environment.system().annotate_system_version(
|
||||
info
|
||||
),
|
||||
is_package_compatible=lambda info, version: environment.system().is_package_compatible(
|
||||
info,
|
||||
version,
|
||||
),
|
||||
auth_checker=lambda plugin, source: access.check(plugin, source),
|
||||
version_compare=lambda source, comparison, target: (
|
||||
compare_version(source, comparison, target) is True
|
||||
),
|
||||
log=environment.logger,
|
||||
)
|
||||
catalog = PluginCatalogFacade(
|
||||
classes=lambda: registry.classes,
|
||||
running=lambda: registry.running,
|
||||
storage=environment.storage,
|
||||
system=environment.system,
|
||||
market_catalog=lambda: environment.catalog_factory(metadata.map),
|
||||
market_loader=lambda market, package_version=None, force=False: (
|
||||
host.get_plugins_from_market(market, package_version, force)
|
||||
),
|
||||
async_market_loader=lambda market, package_version=None, force=False: (
|
||||
host.async_get_plugins_from_market(
|
||||
market,
|
||||
package_version,
|
||||
force,
|
||||
)
|
||||
),
|
||||
map_plugin=lambda **kwargs: metadata.map(
|
||||
plugin_id=kwargs["pid"],
|
||||
plugin_info=kwargs["plugin_info"],
|
||||
market=kwargs["market"],
|
||||
installed_plugins=kwargs["installed_apps"],
|
||||
add_time=kwargs["add_time"],
|
||||
package_version=kwargs.get("package_version"),
|
||||
),
|
||||
auth_checker=lambda **kwargs: access.check(**kwargs),
|
||||
plugin_attr=lambda plugin_id, attribute: getattr(
|
||||
registry.instance(plugin_id),
|
||||
attribute,
|
||||
None,
|
||||
),
|
||||
plugin_instance=instances.get,
|
||||
plugin_instances=instances.all,
|
||||
runtime_status=registry.runtime_status,
|
||||
log=environment.logger,
|
||||
)
|
||||
paths = PluginPathResolver(
|
||||
runtime_root=environment.plugins_root,
|
||||
running=lambda: registry.running,
|
||||
system=environment.system,
|
||||
strict_system_version=lambda: not environment.development(),
|
||||
log=environment.logger,
|
||||
)
|
||||
recent_local_sync: dict[str, float] = {}
|
||||
local_sync = LocalPluginSyncService(
|
||||
installed_plugins=lambda: environment.storage().read(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
) or [],
|
||||
candidate=lambda plugin_id: environment.system().local_candidate(plugin_id),
|
||||
system=environment.system,
|
||||
recent_sync=recent_local_sync,
|
||||
log=environment.logger,
|
||||
)
|
||||
dependencies = PluginDependencyService(
|
||||
system=environment.system,
|
||||
instances=instances.all,
|
||||
registry=registry,
|
||||
log=environment.logger,
|
||||
)
|
||||
sync = PluginSyncService(
|
||||
frozen=lambda: environment.system().is_frozen(),
|
||||
installed_plugins=lambda: environment.storage().read(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
) or [],
|
||||
online_plugins=catalog.online,
|
||||
local_plugins=catalog.local_repository,
|
||||
merge_plugins=lambda higher, base, _markets: catalog.merge(higher, base),
|
||||
plugin_exists=catalog.exists,
|
||||
install=lambda plugin_id, repo_url, force, startup_token: environment.system().install_plugin(
|
||||
plugin_id=plugin_id,
|
||||
repo_url=repo_url,
|
||||
force=force,
|
||||
startup_token=startup_token,
|
||||
),
|
||||
log=environment.logger,
|
||||
)
|
||||
def source_plugin_id(plugin_id: str) -> str:
|
||||
"""把虚拟实例归一到持久化的物理源码插件。"""
|
||||
instance = instances.get(plugin_id)
|
||||
return instance.source_plugin_id if instance else plugin_id
|
||||
|
||||
clone = PluginCloneService(
|
||||
plugin_class=registry.plugin_class,
|
||||
plugin_exists=catalog.exists,
|
||||
source_plugin_id=source_plugin_id,
|
||||
save_instance=instances.save,
|
||||
delete_instance=instances.delete,
|
||||
read_config=configs.read,
|
||||
save_config=lambda plugin_id, config: configs.write(
|
||||
plugin_id,
|
||||
config,
|
||||
force=True,
|
||||
),
|
||||
delete_config=lambda plugin_id: configs.delete(plugin_id, force=True),
|
||||
reload_plugin=host.reload_plugin,
|
||||
remove_plugin=host.remove_plugin,
|
||||
log=environment.logger,
|
||||
)
|
||||
projection = PluginProjection(
|
||||
registry.running,
|
||||
environment.logger,
|
||||
environment.remote_entry,
|
||||
)
|
||||
return PluginRuntime(
|
||||
registry=registry,
|
||||
instances=instances,
|
||||
configs=configs,
|
||||
access=access,
|
||||
catalog=catalog,
|
||||
paths=paths,
|
||||
local_sync=local_sync,
|
||||
monitor=PluginMonitorController(
|
||||
runner=host._run_file_watcher,
|
||||
log=environment.logger,
|
||||
),
|
||||
admission=PluginMutationAdmission(),
|
||||
dependencies=dependencies,
|
||||
loader=loader,
|
||||
tools=tools,
|
||||
lifecycle=lifecycle,
|
||||
metadata=metadata,
|
||||
sync=sync,
|
||||
clone=clone,
|
||||
projection=projection,
|
||||
recent_local_sync=recent_local_sync,
|
||||
system=environment.system,
|
||||
)
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Optional, cast
|
||||
|
||||
|
||||
class PluginSystemServices:
|
||||
@@ -91,6 +91,38 @@ class PluginSystemServices:
|
||||
startup_token=startup_token,
|
||||
)
|
||||
|
||||
def remove_plugin_package(self, plugin_id: str) -> bool:
|
||||
"""通过唯一包事务 owner 删除插件物理目录。"""
|
||||
return bool(self.package.remove_plugin(plugin_id))
|
||||
|
||||
def modify_plugin_files(self, **kwargs: Any) -> tuple[bool, str]:
|
||||
"""把旧分身源码改写调用收口到唯一包适配器。"""
|
||||
return cast(tuple[bool, str], self.package._modify_plugin_files(**kwargs))
|
||||
|
||||
def modify_python_file(self, **kwargs: Any) -> tuple[bool, str]:
|
||||
"""把旧 Python 类改写调用收口到唯一包适配器。"""
|
||||
return cast(tuple[bool, str], self.package._modify_python_file(**kwargs))
|
||||
|
||||
def modify_federation_files(self, **kwargs: Any) -> tuple[bool, str]:
|
||||
"""把旧联邦构建产物改写调用收口到唯一包适配器。"""
|
||||
return cast(
|
||||
tuple[bool, str],
|
||||
self.package._modify_federation_files(**kwargs),
|
||||
)
|
||||
|
||||
def rename_federation_assets(
|
||||
self,
|
||||
dist_dir: Path,
|
||||
original_class_name: str,
|
||||
clone_class_name: str,
|
||||
) -> None:
|
||||
"""把旧联邦资源重命名调用收口到唯一包适配器。"""
|
||||
self.package._rename_federation_assets(
|
||||
dist_dir,
|
||||
original_class_name,
|
||||
clone_class_name,
|
||||
)
|
||||
|
||||
|
||||
_services: Optional[PluginSystemServices] = None
|
||||
|
||||
|
||||
@@ -20,37 +20,19 @@ from typing import (
|
||||
|
||||
from watchfiles import watch
|
||||
|
||||
from app.foundation.crypto import RSAUtils
|
||||
from app.foundation.environment import is_free_threaded_runtime, is_gil_enabled
|
||||
from app.foundation.singleton import Singleton
|
||||
from app.foundation.version import compare_version
|
||||
from app.runtime.events import EventHandlerBinding, eventmanager
|
||||
from app.runtime.execution import run_in_threadpool_to_completion
|
||||
from app.runtime.extensions.plugin.access import PluginAccessPolicy
|
||||
from app.runtime.extensions.plugin.admission import PluginMutationAdmission
|
||||
from app.runtime.extensions.plugin.catalog import PluginCatalogFacade
|
||||
from app.runtime.extensions.plugin.clone import PluginCloneService
|
||||
from app.runtime.extensions.plugin.dependency import (
|
||||
PluginDependencyClassification,
|
||||
PluginDependencyInstallResult,
|
||||
PluginDependencyService,
|
||||
)
|
||||
from app.runtime.extensions.plugin.lifecycle import PluginLifecycle
|
||||
from app.runtime.extensions.plugin.loader import PluginLoader
|
||||
from app.runtime.extensions.plugin.metadata import PluginMetadataMapper
|
||||
from app.runtime.extensions.plugin.monitor import (
|
||||
PluginChangeMonitor,
|
||||
PluginMonitorController,
|
||||
)
|
||||
from app.runtime.extensions.plugin.paths import PluginPathResolver
|
||||
from app.runtime.extensions.plugin.monitor import PluginChangeMonitor
|
||||
from app.runtime.extensions.plugin.projection import PluginProjection
|
||||
from app.runtime.extensions.plugin.registry import PluginRegistry
|
||||
from app.runtime.extensions.plugin.storage import PluginConfigStore, PluginInstanceStore, get_plugin_storage
|
||||
from app.runtime.extensions.plugin.sync import (
|
||||
LocalPluginSyncService,
|
||||
PluginSyncService,
|
||||
)
|
||||
from app.runtime.extensions.plugin.system import get_plugin_system
|
||||
from app.runtime.extensions.plugin.runtime import PluginRuntime
|
||||
from app.runtime.extensions.plugin.tools import PluginToolCatalog
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.observability import observe_compat_facade
|
||||
@@ -61,13 +43,14 @@ 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.types import EventType, SystemConfigKey
|
||||
from app.schemas.types import EventType
|
||||
|
||||
LegacyDiagnosticsConfigurator = Callable[..., None]
|
||||
LegacyImportScanner = Callable[..., None]
|
||||
LegacyPluginImportPreparer = Callable[..., None]
|
||||
SiteAuthLevelProvider = Callable[[], int]
|
||||
PluginCatalogFactory = Callable[["PluginManager"], Any]
|
||||
PluginCatalogFactory = Callable[[Callable[..., Any]], Any]
|
||||
PluginRuntimeFactory = Callable[["PluginManager"], PluginRuntime]
|
||||
PluginRouteRefresher = Callable[[str], None]
|
||||
|
||||
|
||||
@@ -84,11 +67,16 @@ def _unavailable_site_auth_level() -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def _unavailable_plugin_catalog_factory(_manager: "PluginManager") -> Any:
|
||||
def _unavailable_plugin_catalog_factory(_mapper: Callable[..., Any]) -> Any:
|
||||
"""在启动组合根尚未装配目录用例时拒绝隐式跨层构造。"""
|
||||
raise RuntimeError("插件目录应用服务尚未由启动组合根装配")
|
||||
|
||||
|
||||
def _unavailable_plugin_runtime_factory(_manager: "PluginManager") -> PluginRuntime:
|
||||
"""拒绝在启动组合根尚未注入依赖图时隐式构造插件 Runtime。"""
|
||||
raise RuntimeError("插件 Runtime 工厂尚未由启动组合根装配")
|
||||
|
||||
|
||||
def _warn_if_plugin_enabled_gil(
|
||||
*,
|
||||
gil_enabled_before: bool,
|
||||
@@ -121,6 +109,7 @@ _legacy_plugin_import_preparer: LegacyPluginImportPreparer = (
|
||||
)
|
||||
_site_auth_level_provider: SiteAuthLevelProvider = _unavailable_site_auth_level
|
||||
_plugin_catalog_factory: PluginCatalogFactory = _unavailable_plugin_catalog_factory
|
||||
_plugin_runtime_factory: PluginRuntimeFactory = _unavailable_plugin_runtime_factory
|
||||
_plugin_route_refresher: PluginRouteRefresher = _unavailable_plugin_route_refresher
|
||||
|
||||
|
||||
@@ -155,12 +144,31 @@ def configure_plugin_catalog_factory(factory: PluginCatalogFactory) -> None:
|
||||
_plugin_catalog_factory = factory
|
||||
|
||||
|
||||
def configure_plugin_runtime_factory(factory: PluginRuntimeFactory) -> None:
|
||||
"""由启动组合根注入完整插件 Runtime 工厂。"""
|
||||
global _plugin_runtime_factory
|
||||
_plugin_runtime_factory = factory
|
||||
|
||||
|
||||
def reset_plugin_runtime_factory() -> None:
|
||||
"""恢复未装配工厂,仅供隔离测试清理进程级依赖。"""
|
||||
global _plugin_runtime_factory
|
||||
_plugin_runtime_factory = _unavailable_plugin_runtime_factory
|
||||
|
||||
|
||||
def configure_plugin_route_refresher(refresher: PluginRouteRefresher) -> None:
|
||||
"""由启动组合根注入热重载后的动态路由投影刷新器。"""
|
||||
global _plugin_route_refresher
|
||||
_plugin_route_refresher = refresher
|
||||
|
||||
|
||||
def _resolve_plugin_handler_instance(
|
||||
owner_class: Type[Any],
|
||||
) -> Optional[EventHandlerBinding]:
|
||||
"""通过当前插件管理器单例解析实例,避免事件总线持有过期对象。"""
|
||||
return PluginManager().resolve_event_handler_instance(owner_class)
|
||||
|
||||
|
||||
@observe_compat_facade("PluginManager")
|
||||
class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""插件管理器"""
|
||||
@@ -169,72 +177,11 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
# 略长于 watchfiles 默认 debounce,吸收包写入完成后才交付的延迟批次。
|
||||
MONITOR_SETTLE_SECONDS = 2.0
|
||||
|
||||
def __init__(self):
|
||||
"""初始化插件注册表、缓存和开发模式监控状态。"""
|
||||
self._plugin_registry = PluginRegistry()
|
||||
# 旧属性继续引用注册表拥有的可变字典,保持插件和测试的访问身份。
|
||||
self._plugins = self._plugin_registry.classes
|
||||
self._running_plugins = self._plugin_registry.running
|
||||
self._plugin_instance_store = PluginInstanceStore(
|
||||
storage=lambda: get_plugin_storage(),
|
||||
)
|
||||
# 配置Key
|
||||
self._config_key: str = "plugin.%s"
|
||||
self._plugin_config_store = PluginConfigStore(
|
||||
storage=lambda: get_plugin_storage(),
|
||||
plugin_exists=lambda pid: bool(self._plugins.get(pid)),
|
||||
key_prefix=self._config_key,
|
||||
)
|
||||
self._plugin_access = PluginAccessPolicy(
|
||||
auth_level=lambda: _site_auth_level_provider(),
|
||||
verify_keys=RSAUtils.verify_rsa_keys,
|
||||
log=logger,
|
||||
)
|
||||
self._plugin_catalog_view = PluginCatalogFacade(
|
||||
classes=lambda: self._plugins,
|
||||
running=lambda: self._running_plugins,
|
||||
storage=lambda: get_plugin_storage(),
|
||||
system=get_plugin_system,
|
||||
market_catalog=lambda: self._plugin_catalog(),
|
||||
market_loader=lambda market, package_version=None, force=False: (
|
||||
self.get_plugins_from_market(market, package_version, force)
|
||||
),
|
||||
async_market_loader=lambda market, package_version=None, force=False: (
|
||||
self.async_get_plugins_from_market(market, package_version, force)
|
||||
),
|
||||
map_plugin=lambda **kwargs: self._process_plugin_info(**kwargs),
|
||||
auth_checker=lambda **kwargs: self.__set_and_check_auth_level(**kwargs),
|
||||
plugin_attr=lambda pid, attr: self.get_plugin_attr(pid, attr),
|
||||
plugin_instance=self.get_plugin_instance,
|
||||
plugin_instances=self.get_plugin_instances,
|
||||
runtime_status=self._plugin_registry.runtime_status,
|
||||
log=logger,
|
||||
)
|
||||
# 本地插件同步写入运行目录后的短时忽略窗口
|
||||
self._recent_local_sync: Dict[str, float] = {}
|
||||
def __init__(self) -> None:
|
||||
"""消费组合根注入的唯一 Runtime,并保留旧私有字段的对象身份。"""
|
||||
self._monitor_suppression_lock = threading.Lock()
|
||||
self._suppressed_monitor_plugins: Dict[str, int] = {}
|
||||
self._monitor_suppressed_until: Dict[str, float] = {}
|
||||
self._plugin_paths = PluginPathResolver(
|
||||
runtime_root=get_runtime_setting('ROOT_PATH') / "app" / "plugins",
|
||||
running=lambda: self._running_plugins,
|
||||
system=get_plugin_system,
|
||||
strict_system_version=lambda: not get_runtime_setting('DEV'),
|
||||
log=logger,
|
||||
)
|
||||
self._local_plugin_sync = LocalPluginSyncService(
|
||||
installed_plugins=lambda: get_plugin_storage().read(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
) or [],
|
||||
candidate=lambda pid: get_plugin_system().local_candidate(pid),
|
||||
system=get_plugin_system,
|
||||
recent_sync=self._recent_local_sync,
|
||||
log=logger,
|
||||
)
|
||||
self._plugin_monitor = PluginMonitorController(
|
||||
runner=self._run_file_watcher,
|
||||
log=logger,
|
||||
)
|
||||
self._plugin_quiesce_lock = threading.RLock()
|
||||
self._plugin_quiesce_future: Optional[
|
||||
concurrent.futures.Future[bool]
|
||||
@@ -242,106 +189,31 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
self._plugin_service_quiesce_future: Optional[
|
||||
concurrent.futures.Future[bool]
|
||||
] = None
|
||||
self._plugin_mutation_admission = PluginMutationAdmission()
|
||||
self._plugin_runtime_closed = False
|
||||
self._plugin_dependencies = PluginDependencyService(
|
||||
system=get_plugin_system,
|
||||
log=logger,
|
||||
)
|
||||
self._plugin_loader = PluginLoader(
|
||||
plugins_root=get_runtime_setting('ROOT_PATH') / "app" / "plugins",
|
||||
import_preparer=lambda **kwargs: _legacy_plugin_import_preparer(**kwargs),
|
||||
import_scanner=lambda **kwargs: _legacy_import_scanner(**kwargs),
|
||||
log=logger,
|
||||
)
|
||||
self._plugin_tool_catalog = PluginToolCatalog(
|
||||
max_attempts=self.AGENT_TOOLS_BUILD_MAX_ATTEMPTS
|
||||
)
|
||||
self._plugin_lifecycle = PluginLifecycle(
|
||||
classes=self._plugins,
|
||||
running=self._running_plugins,
|
||||
load_plugins=lambda pid, installed, check: self._load_runtime_plugins(
|
||||
pid,
|
||||
installed,
|
||||
check,
|
||||
),
|
||||
installed_plugins=lambda: get_plugin_storage().read(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
) or [],
|
||||
plugin_config=self.get_plugin_config,
|
||||
auth_checker=lambda plugin: self.__set_and_check_auth_level(plugin=plugin),
|
||||
clear_modules=lambda pid: self._clear_plugin_modules(pid),
|
||||
clear_tools=self.clear_plugin_agent_tools_cache,
|
||||
enable_events=eventmanager.enable_event_handler,
|
||||
disable_events=eventmanager.disable_event_handler,
|
||||
runtime_status_writer=self._plugin_registry.set_runtime_status,
|
||||
log=logger,
|
||||
event_sender=eventmanager.send_event,
|
||||
)
|
||||
self._plugin_metadata = PluginMetadataMapper(
|
||||
plugin_instance=self._plugin_registry.instance,
|
||||
plugin_class=self._plugin_registry.plugin_class,
|
||||
annotate_system_version=lambda info: get_plugin_system().annotate_system_version(
|
||||
info
|
||||
),
|
||||
is_package_compatible=lambda info, version: get_plugin_system().is_package_compatible(
|
||||
info,
|
||||
version,
|
||||
),
|
||||
auth_checker=lambda plugin, source: self.__set_and_check_auth_level(
|
||||
plugin,
|
||||
source,
|
||||
),
|
||||
version_compare=compare_version,
|
||||
log=logger,
|
||||
)
|
||||
self._plugin_sync = PluginSyncService(
|
||||
frozen=lambda: get_plugin_system().is_frozen(),
|
||||
installed_plugins=lambda: get_plugin_storage().read(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
) or [],
|
||||
online_plugins=lambda: self.get_online_plugins(),
|
||||
local_plugins=lambda: self.get_local_repo_plugins(),
|
||||
merge_plugins=lambda higher, base, _markets: self.process_plugins_list(
|
||||
higher,
|
||||
base,
|
||||
),
|
||||
plugin_exists=lambda plugin_id, version: self.is_plugin_exists(
|
||||
plugin_id,
|
||||
version,
|
||||
),
|
||||
install=lambda plugin_id, repo_url, force, startup_token: get_plugin_system().install_plugin(
|
||||
plugin_id=plugin_id,
|
||||
repo_url=repo_url,
|
||||
force=force,
|
||||
startup_token=startup_token,
|
||||
),
|
||||
log=logger,
|
||||
)
|
||||
self._plugin_clone = PluginCloneService(
|
||||
plugin_class=self._plugin_registry.plugin_class,
|
||||
plugin_exists=lambda plugin_id: self.is_plugin_exists(plugin_id),
|
||||
source_plugin_id=self.get_plugin_source_id,
|
||||
save_instance=self._plugin_instance_store.save,
|
||||
delete_instance=self._plugin_instance_store.delete,
|
||||
read_config=self.get_plugin_config,
|
||||
save_config=lambda plugin_id, config: self.save_plugin_config(
|
||||
plugin_id,
|
||||
config,
|
||||
force=True,
|
||||
),
|
||||
delete_config=lambda plugin_id: self.delete_plugin_config(
|
||||
plugin_id,
|
||||
force=True,
|
||||
),
|
||||
reload_plugin=self.reload_plugin,
|
||||
remove_plugin=self.remove_plugin,
|
||||
log=logger,
|
||||
)
|
||||
self._plugin_runtime = _plugin_runtime_factory(self)
|
||||
self._plugin_registry = self._plugin_runtime.registry
|
||||
self._plugins = self._plugin_registry.classes
|
||||
self._running_plugins = self._plugin_registry.running
|
||||
self._plugin_instance_store = self._plugin_runtime.instances
|
||||
self._plugin_config_store = self._plugin_runtime.configs
|
||||
self._plugin_access = self._plugin_runtime.access
|
||||
self._plugin_catalog_view = self._plugin_runtime.catalog
|
||||
self._recent_local_sync = self._plugin_runtime.recent_local_sync
|
||||
self._plugin_paths = self._plugin_runtime.paths
|
||||
self._local_plugin_sync = self._plugin_runtime.local_sync
|
||||
self._plugin_monitor = self._plugin_runtime.monitor
|
||||
self._plugin_mutation_admission = self._plugin_runtime.admission
|
||||
self._plugin_dependencies = self._plugin_runtime.dependencies
|
||||
self._plugin_loader = self._plugin_runtime.loader
|
||||
self._plugin_tool_catalog = self._plugin_runtime.tools
|
||||
self._plugin_lifecycle = self._plugin_runtime.lifecycle
|
||||
self._plugin_metadata = self._plugin_runtime.metadata
|
||||
self._plugin_sync = self._plugin_runtime.sync
|
||||
self._plugin_clone = self._plugin_runtime.clone
|
||||
# 事件总线只通过通用解析器访问运行中的插件实例。
|
||||
eventmanager.register_handler_instance_resolver(
|
||||
"plugins",
|
||||
self.resolve_event_handler_instance,
|
||||
_resolve_plugin_handler_instance,
|
||||
)
|
||||
def resolve_event_handler_instance(
|
||||
self,
|
||||
@@ -554,47 +426,6 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
self._plugin_mutation_admission.wait_until_idle()
|
||||
return self._plugin_lifecycle.quiesce_handlers()
|
||||
|
||||
@staticmethod
|
||||
def _load_selective_plugins(pid: Optional[str], installed_plugins: List[str],
|
||||
check_module_func: Callable) -> List[Any]:
|
||||
"""
|
||||
选择性加载插件,只import符合条件的插件
|
||||
:param pid: 指定插件ID,为空则加载所有已安装插件
|
||||
:param installed_plugins: 已安装插件列表
|
||||
:param check_module_func: 模块检查函数
|
||||
:return: 插件类列表
|
||||
"""
|
||||
return PluginLoader(
|
||||
plugins_root=get_runtime_setting('ROOT_PATH') / "app" / "plugins",
|
||||
import_preparer=lambda **kwargs: _legacy_plugin_import_preparer(**kwargs),
|
||||
import_scanner=lambda **kwargs: _legacy_import_scanner(**kwargs),
|
||||
log=logger,
|
||||
).load(pid, installed_plugins, check_module_func)
|
||||
|
||||
def _load_runtime_plugins(
|
||||
self,
|
||||
pid: Optional[str],
|
||||
installed_plugins: List[str],
|
||||
check_module_func: Callable[[Any], bool],
|
||||
) -> List[Any]:
|
||||
"""加载物理插件或虚拟实例,并保留旧选择性加载方法的合同。"""
|
||||
if pid:
|
||||
instance = self._plugin_instance_store.get(pid)
|
||||
if instance:
|
||||
return self._plugin_loader.load_instance(instance, check_module_func)
|
||||
return self._plugin_loader.load(pid, installed_plugins, check_module_func)
|
||||
|
||||
plugins = self._plugin_loader.load(
|
||||
None,
|
||||
installed_plugins,
|
||||
check_module_func,
|
||||
)
|
||||
for instance in self._plugin_instance_store.all().values():
|
||||
plugins.extend(
|
||||
self._plugin_loader.load_instance(instance, check_module_func)
|
||||
)
|
||||
return plugins
|
||||
|
||||
@property
|
||||
def running_plugins(self) -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -660,7 +491,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
PluginChangeMonitor(
|
||||
runtime_root=get_runtime_setting('ROOT_PATH') / "app" / "plugins",
|
||||
local_roots=get_plugin_system().local_repo_paths,
|
||||
local_roots=self._plugin_runtime.system().local_repo_paths,
|
||||
stop_event=self._plugin_monitor.stop_event,
|
||||
recent_sync=self._recent_local_sync,
|
||||
federated_change=self._get_federated_plugin_change,
|
||||
@@ -670,7 +501,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
sync_local=self._sync_local_plugin_if_installed,
|
||||
reload_plugin=self._reload_plugin_tree_from_monitor,
|
||||
dependency_manifest_status=(
|
||||
get_plugin_system().dependency_manifest_status
|
||||
self._plugin_runtime.system().dependency_manifest_status
|
||||
),
|
||||
watch=watch,
|
||||
log=logger,
|
||||
@@ -773,6 +604,10 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
except PluginMutationRejectedError as error:
|
||||
logger.warning(str(error))
|
||||
|
||||
def remove_plugin_package(self, plugin_id: str) -> bool:
|
||||
"""把插件物理目录删除委托给唯一包文件事务 owner。"""
|
||||
return self._plugin_runtime.system().remove_plugin_package(plugin_id)
|
||||
|
||||
def reload_plugin(self, plugin_id: str) -> PluginRuntimeStatus:
|
||||
"""
|
||||
将一个插件重新加载到内存
|
||||
@@ -823,20 +658,6 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
),
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _clear_plugin_modules(plugin_id: Optional[str] = None):
|
||||
"""
|
||||
清除插件及其所有子模块的缓存
|
||||
:param plugin_id: 插件ID
|
||||
"""
|
||||
|
||||
return PluginLoader(
|
||||
plugins_root=get_runtime_setting('ROOT_PATH') / "app" / "plugins",
|
||||
import_preparer=lambda **kwargs: _legacy_plugin_import_preparer(**kwargs),
|
||||
import_scanner=lambda **kwargs: _legacy_import_scanner(**kwargs),
|
||||
log=logger,
|
||||
).clear_modules(plugin_id)
|
||||
|
||||
def sync(
|
||||
self,
|
||||
startup_token: object | None = None,
|
||||
@@ -860,82 +681,32 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
manager = PluginManager()
|
||||
with manager.mutation("安装插件依赖"):
|
||||
return PluginDependencyService(
|
||||
system=get_plugin_system,
|
||||
log=logger,
|
||||
).install_missing()
|
||||
return manager._plugin_dependencies.install_missing()
|
||||
|
||||
@staticmethod
|
||||
def install_plugin_missing_dependencies_with_status() -> PluginDependencyInstallResult:
|
||||
"""安装插件缺失依赖并返回缺失项及安装成功状态。"""
|
||||
manager = PluginManager()
|
||||
with manager.mutation("安装插件依赖"):
|
||||
return PluginDependencyService(
|
||||
system=get_plugin_system,
|
||||
log=logger,
|
||||
).install_missing_with_status()
|
||||
return manager._plugin_dependencies.install_missing_with_status()
|
||||
|
||||
@staticmethod
|
||||
async def async_install_plugin_missing_dependencies_with_status() -> PluginDependencyInstallResult:
|
||||
"""在异步启动链中恢复插件依赖并保留取消语义。"""
|
||||
manager = PluginManager()
|
||||
with manager.mutation("安装插件依赖"):
|
||||
return await PluginDependencyService(
|
||||
system=get_plugin_system,
|
||||
log=logger,
|
||||
).async_install_missing_with_status()
|
||||
return await manager._plugin_dependencies.async_install_missing_with_status()
|
||||
|
||||
def classify_plugins(self) -> PluginDependencyClassification:
|
||||
"""按源码依赖状态分类物理插件,并把结果映射到虚拟实例。"""
|
||||
source_classification = PluginDependencyService(
|
||||
system=get_plugin_system,
|
||||
log=logger,
|
||||
).classify_plugins()
|
||||
ready = list(source_classification.ready)
|
||||
missing_dependencies = list(source_classification.missing_dependencies)
|
||||
missing_source = list(source_classification.missing_source)
|
||||
source_ready = set(source_classification.ready)
|
||||
source_pending = set(source_classification.missing_dependencies)
|
||||
for instance in self._plugin_instance_store.all().values():
|
||||
if instance.source_plugin_id in source_ready:
|
||||
ready.append(instance.instance_id)
|
||||
elif instance.source_plugin_id in source_pending:
|
||||
missing_dependencies.append(instance.instance_id)
|
||||
else:
|
||||
missing_source.append(instance.instance_id)
|
||||
return PluginDependencyClassification(
|
||||
ready=tuple(ready),
|
||||
missing_dependencies=tuple(missing_dependencies),
|
||||
missing_source=tuple(missing_source),
|
||||
)
|
||||
"""返回依赖 owner 计算的物理插件与虚拟实例分类。"""
|
||||
return self._plugin_dependencies.classify_plugins()
|
||||
|
||||
def apply_plugin_dependency_classification(
|
||||
self,
|
||||
classification: PluginDependencyClassification,
|
||||
) -> None:
|
||||
"""把源码和依赖分类写入运行状态,已激活插件保持当前结果。"""
|
||||
running_ids = set(self._plugin_registry.running_ids())
|
||||
for plugin_id in classification.missing_source:
|
||||
self._plugin_registry.set_runtime_status(
|
||||
plugin_id,
|
||||
PluginRuntimeStatus.SOURCE_MISSING,
|
||||
)
|
||||
for plugin_id in classification.missing_dependencies:
|
||||
self._plugin_registry.set_runtime_status(
|
||||
plugin_id,
|
||||
PluginRuntimeStatus.DEPENDENCY_PENDING,
|
||||
)
|
||||
for plugin_id in classification.ready:
|
||||
current_status = self._plugin_registry.runtime_status(plugin_id)
|
||||
if (
|
||||
plugin_id in running_ids
|
||||
and current_status is not PluginRuntimeStatus.DEPENDENCY_PENDING
|
||||
):
|
||||
continue
|
||||
self._plugin_registry.set_runtime_status(
|
||||
plugin_id,
|
||||
PluginRuntimeStatus.READY,
|
||||
)
|
||||
"""把分类结果委托依赖 owner 写入唯一运行状态注册表。"""
|
||||
self._plugin_dependencies.apply_classification(classification)
|
||||
|
||||
def set_plugin_settling(self, settling: bool) -> None:
|
||||
"""更新启动后的插件恢复任务状态。"""
|
||||
@@ -1063,16 +834,12 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
return plugin.get_state() if plugin else False
|
||||
|
||||
def _plugin_projection(self) -> PluginProjection:
|
||||
"""构造绑定当前运行态插件注册表的能力投影服务。"""
|
||||
return PluginProjection(
|
||||
self._plugin_registry.running,
|
||||
logger,
|
||||
self.get_plugin_remote_entry,
|
||||
)
|
||||
"""返回类型化 Runtime 持有的唯一能力投影。"""
|
||||
return self._plugin_runtime.projection
|
||||
|
||||
def _plugin_catalog(self) -> Any:
|
||||
"""构造绑定当前市场客户端和插件 DTO 映射器的目录应用服务。"""
|
||||
return _plugin_catalog_factory(self)
|
||||
"""兼容旧私有入口,返回绑定唯一元数据 owner 的目录服务。"""
|
||||
return _plugin_catalog_factory(self._plugin_metadata.map)
|
||||
|
||||
def get_plugin_commands(self, pid: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
@@ -1478,7 +1245,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
original_plugin_class = self._plugins.get(original_id)
|
||||
if not original_plugin_class:
|
||||
return False, f"无法获取原插件类 {original_id}"
|
||||
return get_plugin_system().package._modify_plugin_files(
|
||||
return self._plugin_runtime.system().modify_plugin_files(
|
||||
plugin_dir=plugin_dir,
|
||||
original_class_name=original_plugin_class.__name__,
|
||||
suffix=suffix,
|
||||
@@ -1495,7 +1262,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
兼容旧内部调用,将 Python 文件改写委托给包适配器。
|
||||
"""
|
||||
return get_plugin_system().package._modify_python_file(
|
||||
return PluginManager()._plugin_runtime.system().modify_python_file(
|
||||
file_path=file_path,
|
||||
original_class_name=original_class_name,
|
||||
clone_class_name=clone_class_name,
|
||||
@@ -1510,7 +1277,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
兼容旧内部调用,将联邦文件改写委托给包适配器。
|
||||
"""
|
||||
return get_plugin_system().package._modify_federation_files(
|
||||
return self._plugin_runtime.system().modify_federation_files(
|
||||
dist_dir=dist_dir,
|
||||
original_class_name=original_class_name,
|
||||
clone_class_name=clone_class_name,
|
||||
@@ -1521,7 +1288,7 @@ class PluginManager(ConfigReloadMixin, metaclass=Singleton):
|
||||
"""
|
||||
兼容旧内部调用,将资源重命名委托给包适配器。
|
||||
"""
|
||||
get_plugin_system().package._rename_federation_assets(
|
||||
PluginManager()._plugin_runtime.system().rename_federation_assets(
|
||||
dist_dir,
|
||||
original_class_name,
|
||||
clone_class_name,
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.adapters.external.market import (
|
||||
LOCAL_REPO_PREFIX,
|
||||
VERSION_BACKWARD_COMPATIBLE_FLAGS,
|
||||
PluginHelper,
|
||||
configure_installed_plugins_provider,
|
||||
configure_plugin_install_gateway,
|
||||
)
|
||||
from app.adapters.external.plugin.client import (
|
||||
VERSION_BACKWARD_COMPATIBLE_FLAGS,
|
||||
PluginMarketClient,
|
||||
PluginMarketTransport,
|
||||
PluginPackageSourceClient,
|
||||
split_plugin_market_repo_urls,
|
||||
)
|
||||
from app.adapters.external.plugin.client import PluginMarketClient
|
||||
from app.adapters.external.server import MoviePilotServerHelper
|
||||
from app.adapters.system.host import SystemUtils
|
||||
from app.adapters.system.plugin.dependency import PluginDependencyInstaller
|
||||
@@ -80,13 +85,21 @@ from app.runtime.compat.diagnostics import (
|
||||
from app.runtime.compat.resource_imports import scan_plugin_resource_imports
|
||||
from app.runtime.execution import run_in_threadpool_to_completion
|
||||
from app.runtime.extensions.plugin.dependency import PluginDependencyInstallResult
|
||||
from app.runtime.extensions.plugin.runtime import (
|
||||
PluginRuntime,
|
||||
PluginRuntimeEnvironment,
|
||||
PluginRuntimeHost,
|
||||
build_plugin_runtime,
|
||||
)
|
||||
from app.runtime.extensions.plugin.storage import (
|
||||
PluginStorage,
|
||||
configure_plugin_storage,
|
||||
get_plugin_storage,
|
||||
)
|
||||
from app.runtime.extensions.plugin.system import (
|
||||
PluginSystemServices,
|
||||
configure_plugin_system,
|
||||
get_plugin_system,
|
||||
)
|
||||
from app.runtime.extensions.plugin_manager import (
|
||||
PluginManager,
|
||||
@@ -94,6 +107,7 @@ from app.runtime.extensions.plugin_manager import (
|
||||
configure_plugin_legacy_import_services,
|
||||
configure_plugin_resource_import_preparer,
|
||||
configure_plugin_route_refresher,
|
||||
configure_plugin_runtime_factory,
|
||||
configure_site_auth_level_provider,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
@@ -131,11 +145,36 @@ def _prepare_legacy_plugin_import(*, plugin_id: str, plugin_dir: Path) -> None:
|
||||
)
|
||||
|
||||
|
||||
def build_plugin_runtime_graph(host: PluginRuntimeHost) -> PluginRuntime:
|
||||
"""在启动组合根构造插件 Runtime 的完整依赖图。"""
|
||||
return build_plugin_runtime(
|
||||
host,
|
||||
PluginRuntimeEnvironment(
|
||||
plugins_root=Path(get_runtime_setting('ROOT_PATH')) / "app" / "plugins",
|
||||
storage=lambda: get_plugin_storage(),
|
||||
system=lambda: get_plugin_system(),
|
||||
catalog_factory=lambda mapper: _build_plugin_catalog(mapper),
|
||||
import_preparer=_prepare_legacy_plugin_import,
|
||||
import_scanner=scan_plugin_legacy_imports,
|
||||
auth_level=lambda: SitesHelper().auth_level,
|
||||
remote_entry=host.get_plugin_remote_entry,
|
||||
development=lambda: bool(get_runtime_setting('DEV')),
|
||||
logger=logger,
|
||||
),
|
||||
tool_build_max_attempts=PluginManager.AGENT_TOOLS_BUILD_MAX_ATTEMPTS,
|
||||
)
|
||||
|
||||
|
||||
def configure_plugin_services() -> None:
|
||||
"""把兼容诊断、远程上报和站点认证等级装配到插件管理器。"""
|
||||
plugin_helper = PluginHelper()
|
||||
market_client = PluginMarketClient(plugin_helper)
|
||||
package_manager = PluginPackageManager(plugin_helper)
|
||||
market_transport = PluginMarketTransport()
|
||||
market_client = PluginMarketClient(market_transport)
|
||||
package_manager = PluginPackageManager(
|
||||
source=PluginPackageSourceClient(market_transport),
|
||||
plugin_root=Path(get_runtime_setting('ROOT_PATH')) / "app" / "plugins",
|
||||
)
|
||||
configure_plugin_catalog_factory(_build_plugin_catalog)
|
||||
configure_plugin_runtime_factory(build_plugin_runtime_graph)
|
||||
plugin_manager = get_plugin_manager()
|
||||
inventory_reader = PluginCandidateInventoryReader(
|
||||
market_loader=market_client.get_plugin_index_result,
|
||||
@@ -147,7 +186,9 @@ def configure_plugin_services() -> None:
|
||||
async def refresh_plugin_releases(plugin_id: str, repo_url: str) -> None:
|
||||
"""绕过已有 Release 缓存执行后台刷新。"""
|
||||
async with async_fresh(True):
|
||||
await plugin_helper.async_get_plugin_release_versions(plugin_id, repo_url)
|
||||
await market_transport.async_get_plugin_release_versions(
|
||||
plugin_id, repo_url
|
||||
)
|
||||
|
||||
configure_plugin_release_service(
|
||||
PluginReleaseService(
|
||||
@@ -160,8 +201,8 @@ def configure_plugin_services() -> None:
|
||||
compatible_flags=lambda flag: (
|
||||
VERSION_BACKWARD_COMPATIBLE_FLAGS.get(flag, []) if flag else []
|
||||
),
|
||||
has_release_cache=plugin_helper.async_has_plugin_release_cache,
|
||||
releases=plugin_helper.async_get_plugin_release_versions,
|
||||
has_release_cache=market_transport.async_has_plugin_release_cache,
|
||||
releases=market_transport.async_get_plugin_release_versions,
|
||||
refresh_releases=refresh_plugin_releases,
|
||||
)
|
||||
)
|
||||
@@ -236,7 +277,7 @@ def configure_plugin_services() -> None:
|
||||
inventory=load_inventory,
|
||||
identity=persistence.get_identity,
|
||||
candidate_compatibility=lambda candidate: (
|
||||
plugin_helper.check_plugin_system_version(candidate.dto)
|
||||
market_transport.check_plugin_system_version(candidate.dto)
|
||||
),
|
||||
executor=command,
|
||||
clock=lambda: datetime.now(timezone.utc),
|
||||
@@ -315,13 +356,11 @@ def configure_plugin_services() -> None:
|
||||
configure_installed_plugins_provider(
|
||||
lambda: get_configured_system_config().get(SystemConfigKey.UserInstalledPlugins) or []
|
||||
)
|
||||
configure_plugin_catalog_factory(_build_plugin_catalog)
|
||||
configure_plugin_route_refresher(register_plugin_api)
|
||||
configure_plugin_system(PluginSystemServices(
|
||||
market=market_client,
|
||||
package=package_manager,
|
||||
dependency=PluginDependencyInstaller(
|
||||
plugin_helper,
|
||||
installed_plugins_provider=lambda: get_configured_system_config().get(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
) or [],
|
||||
@@ -450,7 +489,7 @@ def _run_plugin_install_sync(
|
||||
return False, str(error)
|
||||
|
||||
|
||||
def _build_plugin_catalog(manager: PluginManager) -> PluginCatalogService:
|
||||
def _build_plugin_catalog(plugin_mapper: Callable[..., Any]) -> PluginCatalogService:
|
||||
"""在组合根连接目录用例、市场客户端、持久化读取和插件 DTO 映射。"""
|
||||
client = PluginMarketClient()
|
||||
return PluginCatalogService(
|
||||
@@ -459,7 +498,7 @@ def _build_plugin_catalog(manager: PluginManager) -> PluginCatalogService:
|
||||
installed_plugins_provider=lambda: get_configured_system_config().get(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
) or [],
|
||||
plugin_mapper=manager._process_plugin_info,
|
||||
plugin_mapper=plugin_mapper,
|
||||
is_local_repo=PluginMarketClient.is_local_repo_url,
|
||||
version_compare=compare_version,
|
||||
warning=logger.warning,
|
||||
@@ -476,9 +515,9 @@ async def sync_plugins(
|
||||
plugin_manager = None
|
||||
try:
|
||||
loop = main_loop_registry.require()
|
||||
configure_plugin_services()
|
||||
plugin_manager = PluginManager()
|
||||
with plugin_manager.mutation("启动后同步插件"):
|
||||
configure_plugin_services()
|
||||
await get_plugin_identity_migration().migrate()
|
||||
installed_plugins = get_configured_system_config().get(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
|
||||
@@ -347,7 +347,6 @@ async def stop_task_registry(app: FastAPI) -> bool:
|
||||
|
||||
async def prepare_plugin_restore() -> None:
|
||||
"""先恢复未完成安装事务,再加载持久插件备份及其依赖。"""
|
||||
configure_plugin_services()
|
||||
await get_plugin_installation_recovery().replay()
|
||||
await run_in_threadpool_to_completion(SystemChain().restore_plugins)
|
||||
|
||||
@@ -469,10 +468,18 @@ def build_lifecycle_components(app: FastAPI) -> tuple[LifecycleComponent, ...]:
|
||||
start_order=60,
|
||||
start_timeout_seconds=30,
|
||||
),
|
||||
LifecycleComponent(
|
||||
name="插件服务装配",
|
||||
dependencies=("路由",),
|
||||
start=configure_plugin_services,
|
||||
start_order=65,
|
||||
start_timeout_seconds=30,
|
||||
),
|
||||
LifecycleComponent(
|
||||
name="模块服务",
|
||||
dependencies=(
|
||||
"路由",
|
||||
"插件服务装配",
|
||||
"站点访问端口",
|
||||
"Chain 外部端口",
|
||||
"Chain 网络端口",
|
||||
|
||||
Reference in New Issue
Block a user