fix(plugin): fall back from invalid market mirrors (#7464)

* fix(plugin): fall back from invalid market mirrors

* fix(plugin): satisfy market API gates
This commit is contained in:
jxxghp
2026-11-19 00:34:17 +08:00
committed by GitHub
parent cd11bbe3bc
commit d9f64f3043
15 changed files with 556 additions and 90 deletions

View File

@@ -90,13 +90,19 @@ _PLUGIN_INDEX_FETCH_GATE = threading.BoundedSemaphore(
)
class _PluginIndexTooLargeError(RuntimeError):
class _PluginIndexReadError(RuntimeError):
"""
传输或解析未能确认索引存在状态。
"""
class _PluginIndexTooLargeError(_PluginIndexReadError):
"""
插件索引的声明长度或实际读取字节超过资源边界。
"""
class _PluginIndexUnavailableError(RuntimeError):
class _PluginIndexUnavailableError(_PluginIndexReadError):
"""
插件索引连接或 HTTP 状态暂时失败,可短暂缓存并保留库存不完整语义。
"""
@@ -968,6 +974,10 @@ class PluginMarketTransport(metaclass=WeakSingleton):
def __read_plugin_index_response(cls, response: Response) -> tuple[int, str]:
"""
从同步流式响应读取有界的解压后索引文本。
:param response: 当前出口返回的开放响应流
:return: 状态码与正文;非 200 响应不读取正文
:raises _PluginIndexTooLargeError: 声明长度或已读取字节数超过上限
"""
status_code = response.status_code
if status_code != 200:
@@ -994,6 +1004,10 @@ class PluginMarketTransport(metaclass=WeakSingleton):
) -> tuple[int, str]:
"""
从异步流式响应读取有界的解压后索引文本。
:param response: 当前出口返回的开放异步流
:return: 状态码与正文;非 200 响应不读取正文
:raises _PluginIndexTooLargeError: 声明长度或已读取字节数超过上限
"""
status_code = response.status_code
if status_code != 200:
@@ -1049,9 +1063,15 @@ class PluginMarketTransport(metaclass=WeakSingleton):
url: str,
headers: Optional[dict[str, str]] = None,
timeout: Optional[int] = PLUGIN_INDEX_REQUEST_TIMEOUT,
) -> Optional[tuple[int, str]]:
) -> Optional[PluginIndex]:
"""
按 GitHub 降级顺序流式读取同步插件索引,并限制解压后字节数。
按 GitHub 降级顺序流式读取并验证同步插件索引。
:param url: GitHub 原始索引地址
:param headers: 仓库请求头
:param timeout: 单出口请求超时秒数
:return: 有效索引,或以 None 表示原始出口确认索引不存在
:raises _PluginIndexReadError: 所有出口均未返回可判定结果
"""
strategies = cls._build_github_request_strategies(
url=url,
@@ -1059,6 +1079,7 @@ class PluginMarketTransport(metaclass=WeakSingleton):
timeout=timeout,
)
for strategy_name, target_url, request_params in strategies:
from_mirror = strategy_name == "镜像站"
logger.debug(
f"[GitHub] 尝试使用策略:{strategy_name} 请求插件索引:{target_url}"
)
@@ -1068,19 +1089,19 @@ class PluginMarketTransport(metaclass=WeakSingleton):
url=target_url,
raise_exception=True,
) as response:
if response is None:
continue
return cls.__read_plugin_index_response(response)
except _PluginIndexTooLargeError:
raise
raw = cls.__read_plugin_index_response(response) if response is not None else None
return cls._resolve_plugin_index_result(raw, from_mirror=from_mirror)
except _PluginIndexReadError as error:
if not from_mirror:
raise
logger.warning(f"[GitHub] 镜像站未返回有效插件索引,将使用原始出口:{error}")
# 失败后尝试下一传输策略
except Exception as error: # noqa: BLE001
logger.error(
f"[GitHub] 插件索引请求失败,策略:{strategy_name},"
f"URL:{target_url},错误:{_format_request_error(error)}"
)
logger.error(f"[GitHub] 所有策略均无法读取插件索引,URL:{url}")
return None
raise _PluginIndexUnavailableError("插件索引请求失败:连接失败")
@classmethod
async def __async_request_plugin_index_with_fallback(
@@ -1088,9 +1109,15 @@ class PluginMarketTransport(metaclass=WeakSingleton):
url: str,
headers: Optional[dict[str, str]] = None,
timeout: Optional[int] = PLUGIN_INDEX_REQUEST_TIMEOUT,
) -> Optional[tuple[int, str]]:
) -> Optional[PluginIndex]:
"""
按 GitHub 降级顺序流式读取异步插件索引,并限制解压后字节数。
按 GitHub 降级顺序流式读取并验证异步插件索引。
:param url: GitHub 原始索引地址
:param headers: 仓库请求头
:param timeout: 单出口请求超时秒数
:return: 有效索引,或以 None 表示原始出口确认索引不存在
:raises _PluginIndexReadError: 所有出口均未返回可判定结果
"""
strategies = cls._build_github_request_strategies(
url=url,
@@ -1098,6 +1125,7 @@ class PluginMarketTransport(metaclass=WeakSingleton):
timeout=timeout,
)
for strategy_name, target_url, request_params in strategies:
from_mirror = strategy_name == "镜像站"
logger.debug(
f"[GitHub] 尝试使用策略:{strategy_name} 请求插件索引:{target_url}"
)
@@ -1107,19 +1135,22 @@ class PluginMarketTransport(metaclass=WeakSingleton):
url=target_url,
raise_exception=True,
) as response:
if response is None:
continue
return await cls.__async_read_plugin_index_response(response)
except _PluginIndexTooLargeError:
raise
raw = (
await cls.__async_read_plugin_index_response(response)
if response is not None else None
)
return cls._resolve_plugin_index_result(raw, from_mirror=from_mirror)
except _PluginIndexReadError as error:
if not from_mirror:
raise
logger.warning(f"[GitHub] 镜像站未返回有效插件索引,将使用原始出口:{error}")
# 失败后尝试下一传输策略
except Exception as error: # noqa: BLE001
logger.error(
f"[GitHub] 插件索引请求失败,策略:{strategy_name},"
f"URL:{target_url},错误:{_format_request_error(error)}"
)
logger.error(f"[GitHub] 所有策略均无法读取插件索引,URL:{url}")
return None
raise _PluginIndexUnavailableError("插件索引请求失败:连接失败")
@classmethod
def _resolve_plugin_index_response(
@@ -1140,24 +1171,27 @@ class PluginMarketTransport(metaclass=WeakSingleton):
def _resolve_plugin_index_result(
cls,
response: Optional[tuple[int, str]],
*,
from_mirror: bool = False,
) -> Optional[PluginIndex]:
"""
把传输结果统一映射为索引读取合同。
:param response: 传输层返回的状态码和已受限响应文本;None 表示连接失败
:param from_mirror: 是否由镜像站返回;镜像 404 无法证明原始索引不存在
:return: 有效索引,或以 None 表示仓库明确不存在该索引
:raises RuntimeError: 连接失败、非成功状态或响应格式无效
:raises _PluginIndexReadError: 连接失败、非成功状态或响应格式无效
"""
if response is None:
raise _PluginIndexUnavailableError("插件索引请求失败:连接失败")
status_code, content = response
if status_code == 404:
if status_code == 404 and not from_mirror:
return None
if status_code != 200:
raise _PluginIndexUnavailableError(f"插件索引请求失败:HTTP {status_code}")
payload = cls.__parse_plugin_index_response(content)
if payload is None:
raise RuntimeError("插件索引响应格式无效")
raise _PluginIndexReadError("插件索引响应格式无效")
return payload
@staticmethod
@@ -1353,11 +1387,10 @@ class PluginMarketTransport(metaclass=WeakSingleton):
在共享进程级闸门内完成一次同步索引读取。
"""
with _PLUGIN_INDEX_FETCH_GATE:
response = self.__request_plugin_index_with_fallback(
return self.__request_plugin_index_with_fallback(
package_url,
headers=headers,
)
return self._resolve_plugin_index_result(response)
async def _fetch_plugin_index_async(
self,
@@ -1369,13 +1402,12 @@ class PluginMarketTransport(metaclass=WeakSingleton):
"""
await self._acquire_index_fetch_slot()
try:
response = await self.__async_request_plugin_index_with_fallback(
return await self.__async_request_plugin_index_with_fallback(
package_url,
headers=headers,
)
finally:
_PLUGIN_INDEX_FETCH_GATE.release()
return self._resolve_plugin_index_result(response)
async def _fetch_plugin_index_async_task(
self,

View File

@@ -40,7 +40,10 @@ from app.api.response import (
)
from app.application.commands import init_commands
from app.application.configuration import get_api_runtime_config_snapshot, get_configured_system_config
from app.application.plugin.catalog import get_plugin_catalog_query
from app.application.plugin.catalog import (
PluginMarketUnavailableError,
get_plugin_catalog_query,
)
from app.application.plugin.config import PluginConfigCommand
from app.application.plugin.data import PluginDataQueryService, PluginDataSummaryService
from app.application.plugin.folders import remove_plugin_from_folders
@@ -196,7 +199,10 @@ def _verify_plugin_static_file_access(
@router.get(
"/", summary="所有插件", response_model=List[_SchemaPlugin], openapi_extra={COLLECTION_TOTAL_OPENAPI_KEY: True}
"/",
summary="所有插件",
response_model=List[_SchemaPlugin],
openapi_extra={COLLECTION_TOTAL_OPENAPI_KEY: True},
)
async def all_plugins(
_: ApiPrincipal = Depends(get_current_active_superuser_async),
@@ -206,12 +212,34 @@ async def all_plugins(
max_results: Annotated[Optional[int], Query(ge=1, le=200)] = None,
page: CompatiblePageParam = None,
count: CompatibleCountParam = None,
response: Response = None, # type: ignore[assignment]
response: Response = cast(Response, None),
) -> List[_SchemaPlugin]:
"""
查询插件清单;未指定分页或限量时返回完整清单。
市场视图没有在线候选且有索引读取失败时返回依赖失败。
:param _: 已认证的超级管理员
:param state: 插件范围,支持 installed、market 或 all
:param force: 是否强制刷新插件市场
:param query: 可选的插件名称或描述检索词
:param max_results: 旧版调用可选的结果数上限
:param page: 可选的页码
:param count: 可选的每页数量
:param response: 用于写入完整结果数量的 HTTP 响应
:return: 按范围、检索条件和分页参数筛选后的插件列表
:raises HTTPException: 市场依赖读取失败且无在线候选时返回 HTTP 424
"""
plugins = await get_plugin_catalog_query().query(state=state or "all", force=force)
try:
plugins = await get_plugin_catalog_query().query(
state=state or "all",
force=force,
)
except PluginMarketUnavailableError as error:
raise HTTPException(
status_code=status.HTTP_424_FAILED_DEPENDENCY,
detail=str(error),
) from error
if query:
plugins = [item["plugin"] for item in search_plugin_candidates(query, plugins)]
if response is not None:

View File

@@ -36,6 +36,12 @@ ProgressCallback = Callable[..., Any]
DEFAULT_MARKET_FETCH_CONCURRENCY = 5
class PluginMarketUnavailableError(RuntimeError):
"""
有市场索引读取失败,且未取得可用候选,无法确认市场为空。
"""
@dataclass(frozen=True, slots=True)
class _CatalogLoadRequest:
"""
@@ -169,16 +175,20 @@ class PluginCatalogService:
self,
request: _CatalogLoadRequest,
online_plugins: Optional[dict[str, dict[str, Any]]],
) -> list[Any]:
) -> Optional[list[Any]]:
"""
统一加载失败告警与在线目录到插件 DTO 的投影。
:param request: 本次读取的市场和代际参数
:param online_plugins: 已读取的索引;None 表示传输或解析失败
:return: 映射后的插件目录;索引读取失败时返回 None
"""
if online_plugins is None:
self._warning(
f"获取{request.package_version if request.package_version else ''}插件库失败:"
f"{request.market},请检查 GitHub 网络连接"
)
return []
return None
return self._map_plugins(
online_plugins, request.market, request.package_version
)
@@ -202,7 +212,7 @@ class PluginCatalogService:
self._market_loader(
request.market, request.package_version, request.force
),
)
) or []
async def async_load(
self,
@@ -211,7 +221,28 @@ class PluginCatalogService:
force: bool = False,
) -> list[Any]:
"""
异步读取并映射指定市场和插件代际。
异步读取指定市场,沿用单仓目录读取失败时返回空列表的约定。
:param market: 插件市场仓库地址
:param package_version: 要读取的索引代际;None 表示基础索引
:param force: 是否跳过读取缓存
:return: 映射后的插件目录,读取失败时为空
"""
return await self.async_read(market, package_version, force) or []
async def async_read(
self,
market: str,
package_version: Optional[str] = None,
force: bool = False,
) -> Optional[list[Any]]:
"""
异步读取并映射指定索引,保留失败状态供市场聚合使用。
:param market: 插件市场仓库地址
:param package_version: 要读取的索引代际;None 表示基础索引
:param force: 是否跳过读取缓存
:return: 映射后的插件目录,读取失败时返回 None
"""
request = PluginCatalogService._load_request(
market, package_version, force
@@ -277,6 +308,28 @@ class PluginCatalogService:
(higher_plugins if is_higher else base_plugins).extend(plugins)
return self.merge(higher_plugins, base_plugins, markets)
@staticmethod
def _require_available_market_candidates(
*,
required: bool,
candidates: list[Any],
expected_reads: int,
successful_reads: int,
) -> None:
"""
在市场页候选为空且读取不完整时保留上游依赖错误。
:param required: 调用方是否需要确认市场状态
:param candidates: 已成功读取仓库映射后的候选
:param expected_reads: 本轮预期的仓库和代际读取数
:param successful_reads: 已成功返回可判定索引的读取数
:raises PluginMarketUnavailableError: 存在失败读取且没有可展示候选
"""
if required and not candidates and successful_reads < expected_reads:
raise PluginMarketUnavailableError(
"插件市场索引暂时无法读取,请检查 GitHub 网络连接和代理配置"
)
async def async_collect(
self,
*,
@@ -285,13 +338,24 @@ class PluginCatalogService:
force: bool,
loader: Callable[
[str, Optional[str], bool],
Awaitable[list[Any]],
Awaitable[Optional[list[Any]]],
],
preserve_sources: bool = False,
require_available: bool = False,
progress_callback: Optional[ProgressCallback] = None,
) -> list[Any]:
"""
异步读取多个市场和代际,并按调用方需要合并或保留仓库候选。
:param markets: 本轮读取的仓库地址,顺序决定合并优先级
:param compatible_flags: 要读取的插件代际及其优先级
:param force: 是否跳过索引缓存
:param loader: 单个市场和代际的异步读取入口;失败时返回 None 或抛错
:param preserve_sources: 是否保留每个仓库的候选,不跨仓去重
:param require_available: 是否在没有候选且有索引读取失败时报告市场不可用
:param progress_callback: 可选的进度更新回调
:return: 合并或保留来源后的插件目录
:raises PluginMarketUnavailableError: 要求确认市场可用,但存在失败且没有候选
"""
semaphore = asyncio.Semaphore(self._max_concurrency)
@@ -300,15 +364,15 @@ class PluginCatalogService:
package_version: Optional[str],
result_version: str,
task_index: int,
) -> tuple[int, str, list[Any]]:
) -> tuple[int, str, Optional[list[Any]]]:
"""
读取一个市场代际并保留创建时的稳定任务序号。
"""
async with semaphore:
plugins = await loader(market, package_version, force)
return task_index, result_version, plugins or []
return task_index, result_version, plugins
tasks: list[asyncio.Task[tuple[int, str, list[Any]]]] = []
tasks: list[asyncio.Task[tuple[int, str, Optional[list[Any]]]]] = []
for market in markets:
tasks.append(asyncio.create_task(
fetch(market, None, "base_version", len(tasks)),
@@ -323,10 +387,10 @@ class PluginCatalogService:
try:
higher_plugins: list[Any] = []
base_plugins: list[Any] = []
task_results: dict[int, tuple[str, list[Any]]] = {}
if tasks:
total_tasks = len(tasks)
finished_tasks = 0
task_results: dict[int, tuple[str, list[Any]]] = {}
if progress_callback:
progress_callback(
value=0,
@@ -336,7 +400,8 @@ class PluginCatalogService:
for completed_task in asyncio.as_completed(tasks):
try:
task_index, version, plugins = await completed_task
task_results[task_index] = (version, plugins)
if plugins is not None:
task_results[task_index] = (version, plugins)
except Exception as err:
self._error(f"获取插件市场数据失败:{str(err)}")
finished_tasks += 1
@@ -359,6 +424,12 @@ class PluginCatalogService:
if preserve_sources
else self.merge(higher_plugins, base_plugins, markets)
)
self._require_available_market_candidates(
required=require_available,
candidates=result,
expected_reads=len(tasks),
successful_reads=len(task_results),
)
if progress_callback:
progress_callback(value=100, text="插件市场缓存刷新完成")
return result
@@ -581,6 +652,11 @@ class PluginCatalogQuery:
) -> list[Plugin]:
"""
按 installed、market 或 all 返回插件页所需稳定目录。
:param state: 目录范围;market 失败时传播市场不可用状态
:param force: 是否强制刷新在线目录
:return: 按所选范围筛选后的插件目录
:raises PluginMarketUnavailableError: 市场视图没有在线候选且有索引读取失败
"""
installed_plugins = self._installed_plugins()
if state == "installed":
@@ -589,7 +665,12 @@ class PluginCatalogQuery:
local_plugins = self._local_plugins()
not_installed = [plugin for plugin in local_plugins if not plugin.installed]
local_repo_plugins = self._local_repo_plugins()
online_plugins = await self._online_candidates(force)
try:
online_plugins = await self._online_candidates(force)
except PluginMarketUnavailableError:
if state == "market" and not local_repo_plugins and not not_installed:
raise
online_plugins = []
installed_ids = [plugin.id for plugin in installed_plugins if plugin.id]
candidates = (
self._process_plugins(online_plugins + local_repo_plugins, [])

View File

@@ -326,6 +326,7 @@ class PluginCatalogFacade:
:param force: 是否忽略索引缓存
:param repo_url: 可选的目标仓库;未配置或非法来源返回空列表
:return: 指定来源或全部配置市场的候选
:raises PluginMarketUnavailableError: 读取全市场时存在索引失败且没有可用候选
"""
plugin_market = get_runtime_setting('PLUGIN_MARKET')
if not plugin_market:
@@ -336,14 +337,16 @@ class PluginCatalogFacade:
markets = [market for market in markets if target and market.lower() == target.lower()]
if not markets:
return []
result: list[Plugin] = await self._market_catalog().async_collect(
market_catalog = self._market_catalog()
result: list[Plugin] = await market_catalog.async_collect(
markets=markets,
compatible_flags=self._system().compatible_flags(
get_runtime_setting('VERSION_FLAG')
),
force=force,
loader=self._async_market_loader,
loader=market_catalog.async_read if repo_url is None else self._async_market_loader,
preserve_sources=True,
require_available=repo_url is None,
)
return result

View File

@@ -46,6 +46,10 @@ Server 使用独立 SQL 表长期保存关系,不属于识别缓存清理范
### 插件安装前说明入口
`GET /api/v1/plugin/?state=market` 在没有在线候选且存在插件索引读取失败时返回 HTTP `424`,
并提示检查 GitHub 网络连接和代理配置。已确认的空索引以及缺少单个包代际仍是成功读取;
请求 `state=all` 时,本地已安装插件照常返回。
`GET /api/v1/plugin/history/{plugin_id}?force=false` 读取单个已安装插件或分身的元数据,
只查询其可信绑定仓库,不聚合全部插件市场。未安装时返回 404,尚未绑定来源时保留本地快照;
`force=true` 可跳过索引缓存,该接口的默认强制刷新语义保持不变。

View File

@@ -18,7 +18,7 @@ if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
# 与对应 SKILL.md 同步维护,重新生成不能回退用户同步所需的版本。
MOVIEPILOT_API_SKILL_VERSION = "77"
MOVIEPILOT_API_SKILL_VERSION = "78"
DATABASE_OPERATION_SKILL_VERSION = "20"
@@ -344,6 +344,11 @@ _OPERATION_NOTES: dict[str, list[str]] = {
"It never stops a plugin or deletes plugin data, databases, or files. Rows with settings, "
"clones, missing rows, or mixed scopes are rejected.",
],
"plugin.market": [
"- If the market view has no online candidates and one or more configured index reads fail, "
"the endpoint returns HTTP `424` with a retryable index-read error instead of an empty list. "
"A confirmed empty index or an absent package generation remains a successful read.",
],
"library.exists": [
"- **Agent note:** The media-type field name is `mtype` (placed inside `query`). "
"Do **not** reuse the `type` field from the recognition result — `type` is not a "

View File

@@ -1,6 +1,6 @@
---
name: moviepilot-api
version: 77
version: 78
description: >-
Use this skill for MoviePilot product operations such as media search, torrent
search, downloads, subscriptions, library checks, sites, storage, workflows,

View File

@@ -207,6 +207,7 @@ Identity scope: `admin`; required role: `system_admin`.
- `path_params`: none
- `query`: `count` (integer|null): 旧版完整列表接口的可选每页条数;提供 page 或 count 即启用分页,此时省略 count 使用 50 条。; `force` (boolean; default `False`): 为 true 时强制刷新市场或安装插件。; `max_results` (integer|null): 插件目录结果数上限,范围 1 至 200;省略时返回完整目录。; `page` (integer|null): 旧版完整列表接口的可选页码,从 1 开始;同时省略 page 和 count 时保留原有完整结果。; `query` (string|null): 可选关键词,匹配插件标识、名称、说明和作者,不区分大小写。; `state*` (string=market): 固定为 market,仅选择该状态的插件目录条目。
- `body`: none
- If the market view has no online candidates and one or more configured index reads fail, the endpoint returns HTTP `424` with a retryable index-read error instead of an empty list. A confirmed empty index or an absent package generation remains a successful read.
### `plugin.market.sync_wiki`
`POST /api/v1/system/setting/PLUGIN_MARKET/sync-wiki`; policy effect: `external_side_effect`.

View File

@@ -528,16 +528,6 @@
"statement": "@router.get('/passkey/list', summary='获取当前用户的 PassKey 列表', response_model=_SchemaResponse[list[_SchemaPasskeyInfo]], openapi_extra={COLLECTION_TOTAL_OPENAPI_KEY: True})\ndef passkey_list(current_user: Annotated[ApiPrincipal, Depends(get_current_active_user)], response: Response=None, service: PasskeyService=Depends(get_passkey_service), page: CompatiblePageParam=None, count: CompatibleCountParam=None) -> Any:",
"reason": "fastapi-response-default"
},
{
"path": "app/api/endpoints/plugin.py",
"owner": "all_plugins",
"codes": [
"assignment"
],
"fingerprint": "5f6a039d011683394079e360301c9a5ea1b5f5aa09ee4e4826c56fdaff1aaf4f",
"statement": "@router.get('/', summary='所有插件', response_model=List[_SchemaPlugin], openapi_extra={COLLECTION_TOTAL_OPENAPI_KEY: True})\nasync def all_plugins(_: ApiPrincipal=Depends(get_current_active_superuser_async), state: Optional[str]='all', force: bool=False, query: Optional[str]=None, max_results: Annotated[Optional[int], Query(ge=1, le=200)]=None, page: CompatiblePageParam=None, count: CompatibleCountParam=None, response: Response=None) -> List[_SchemaPlugin]:",
"reason": "fastapi-response-default"
},
{
"path": "app/api/endpoints/pluginclone.py",
"owner": "plugin_restorable_instances",

View File

@@ -130,7 +130,7 @@ def test_modified_builtin_skills_have_incremented_versions() -> None:
"database-operation": "20",
"feedback-issue": "12",
"anysearch": "3",
"moviepilot-api": "77",
"moviepilot-api": "78",
"moviepilot-update": "7",
"organize-files": "6",
"transfer-failed-retry": "7",

View File

@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, Mock
import pytest
from app.adapters.external.plugin.client import PluginMarketTransport
from app.adapters.external.plugin.client import PluginIndex, PluginMarketTransport
from app.adapters.system.plugin.dependency import PluginDependencyInstaller
from app.adapters.system.plugin.package import PluginPackageManager
from app.runtime import cache as cache_module
@@ -45,19 +45,19 @@ async def test_plugin_index_sync_async_result_contract_is_identical(
monkeypatch.setattr(cache_module.MemoryBackend, "_region_caches", {})
transport = PluginMarketTransport()
def request(_url: str, *, headers: dict) -> tuple[int, str] | None:
def request(_url: str, *, headers: dict) -> PluginIndex | None:
"""
返回本参数用例的固定同步传输结果。
"""
return response
return transport._resolve_plugin_index_result(response)
async def async_request(
_url: str, *, headers: dict
) -> tuple[int, str] | None:
) -> PluginIndex | None:
"""
返回与同步入口相同的异步传输结果。
"""
return response
return transport._resolve_plugin_index_result(response)
monkeypatch.setattr(transport, SYNC_INDEX_REQUEST, request)
monkeypatch.setattr(transport, ASYNC_INDEX_REQUEST, async_request)

View File

@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock
import pytest
from app.application.plugin.catalog import PluginCatalogService, PluginMarketUnavailableError
from app.runtime import log as log_module
from app.runtime.extensions.plugin.catalog import PluginCatalogFacade
from app.runtime.log import set_plugin_instance_log_level
@@ -76,6 +77,44 @@ async def test_source_candidates_only_load_selected_configured_repository(monkey
assert collect.await_args.kwargs["compatible_flags"] == ["v3", "v2"]
@pytest.mark.asyncio
async def test_catalog_warns_when_market_candidates_cannot_be_loaded(monkeypatch):
"""
全市场查询保留索引失败,单仓文档查询继续返回空候选。
"""
from app.runtime.extensions.plugin import catalog as catalog_module
repo = "https://github.com/Example/Plugins"
warnings: list[str] = []
loader = AsyncMock(return_value=None)
service = PluginCatalogService(
market_loader=lambda *_args: None,
async_market_loader=loader,
installed_plugins_provider=list,
plugin_mapper=lambda *_args: None,
is_local_repo=lambda _value: False,
version_compare=lambda *_args: False,
warning=warnings.append,
error=warnings.append,
)
monkeypatch.setattr(catalog_module, "get_runtime_setting", lambda key: {
"PLUGIN_MARKET": repo,
"VERSION_FLAG": "v3",
}[key])
facade = _facade(
system=lambda: SimpleNamespace(compatible_flags=lambda _flag: ["v3"]),
market_catalog=lambda: service,
async_market_loader=service.async_load,
)
with pytest.raises(PluginMarketUnavailableError, match="插件市场索引暂时无法读取"):
await facade.async_online_candidates(force=True)
loader.assert_any_await(repo, "v3", True)
assert await facade.async_online_candidates(repo_url=repo) == []
assert len(warnings) == 4
@pytest.mark.asyncio
async def test_async_online_normalizes_market_configuration(monkeypatch) -> None:
"""

View File

@@ -3,12 +3,15 @@
"""
import asyncio
from unittest.mock import Mock
from unittest.mock import AsyncMock, Mock
import pytest
from packaging.version import Version
from app.application.plugin.catalog import PluginCatalogService
from app.application.plugin.catalog import (
PluginCatalogService,
PluginMarketUnavailableError,
)
from app.runtime.extensions.plugin.metadata import PluginMetadataMapper
from app.schemas.plugin import Plugin
@@ -209,6 +212,7 @@ async def test_async_collect_isolates_failure_and_completes_progress():
compatible_flags=["v3"],
force=True,
loader=loader,
require_available=True,
progress_callback=progress,
)
@@ -221,6 +225,53 @@ async def test_async_collect_isolates_failure_and_completes_progress():
assert progress.call_args_list[-1].kwargs["value"] == 100
@pytest.mark.asyncio
@pytest.mark.parametrize("base_index", [None, {}], ids=["all-failed", "base-absent"])
async def test_async_collect_reports_failure_without_candidates(base_index):
"""
没有候选且存在读取失败时报告市场不可用,已确认缺少基础索引也不能掩盖失败。
"""
warnings = Mock()
service = _service(
async_market_loader=AsyncMock(side_effect=[base_index, None, None]),
warning=warnings,
)
with pytest.raises(PluginMarketUnavailableError, match="插件市场索引暂时无法读取"):
await service.async_collect(
markets=["https://market-a"],
compatible_flags=["v3", "v2"],
force=False,
loader=service.async_read,
require_available=True,
)
assert warnings.call_count == (3 if base_index is None else 2)
@pytest.mark.asyncio
async def test_async_collect_keeps_valid_empty_market_results():
"""
成功读取到的空目录仍是有效结果,不能误报为网络不可用。
"""
errors = Mock()
service = _service(
async_market_loader=AsyncMock(return_value={}),
error=errors,
)
result = await service.async_collect(
markets=["https://market-empty"],
compatible_flags=["v3"],
force=False,
loader=service.async_read,
require_available=True,
)
assert result == []
errors.assert_not_called()
@pytest.mark.asyncio
async def test_async_collect_preserves_each_repository_update_candidate():
"""

View File

@@ -11,7 +11,7 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import Request
from fastapi import FastAPI, Request
from starlette.responses import Response
from starlette.testclient import TestClient
@@ -32,7 +32,10 @@ from app.api.endpoints.plugin import (
)
from app.api.endpoints.system import sync_plugin_market_from_wiki
from app.application.plugin import release as release_module
from app.application.plugin.catalog import PluginCatalogQuery
from app.application.plugin.catalog import (
PluginCatalogQuery,
PluginMarketUnavailableError,
)
from app.application.plugin.config import PluginConfigCommand
from app.application.plugin.declaration import PluginDeclaredMetadata
from app.application.plugin.identity import (
@@ -110,6 +113,106 @@ def _catalog_query(plugin_manager: MagicMock, persistence: MagicMock) -> PluginC
)
def test_all_plugins_returns_failed_dependency_for_unavailable_market(monkeypatch):
"""
市场不可用时 HTTP 接口返回 424 和可执行的错误提示。
"""
message = "插件市场索引暂时无法读取,请检查 GitHub 网络连接和代理配置"
catalog = SimpleNamespace(
query=AsyncMock(side_effect=PluginMarketUnavailableError(message))
)
monkeypatch.setattr(
plugin_endpoint,
"get_plugin_catalog_query",
lambda: catalog,
)
api = FastAPI()
api.include_router(plugin_endpoint.router, prefix="/api/v1/plugin")
api.dependency_overrides[plugin_endpoint.get_current_active_superuser_async] = lambda: None
with TestClient(api) as client:
response = client.get("/api/v1/plugin/", params={"state": "market", "force": "true"})
catalog.query.assert_awaited_once_with(state="market", force=True)
assert response.status_code == 424
assert response.json()["detail"] == message
@pytest.mark.asyncio
@pytest.mark.parametrize("state", ["all", "installed"])
async def test_all_plugins_query_keeps_installed_view_when_market_is_unavailable(state: str):
"""
市场不可用时仍允许 all 视图返回本地已安装插件。
"""
installed = schemas.Plugin(id="Installed", installed=True)
online_candidates = AsyncMock(side_effect=PluginMarketUnavailableError("索引读取失败"))
query = PluginCatalogQuery(
installed_plugins=lambda: [installed],
local_plugins=lambda: [installed],
local_repo_plugins=lambda: [],
online_candidates=online_candidates,
process_plugins=lambda higher, base: higher + base,
identities=AsyncMock(return_value=[]),
free_threaded=lambda: False,
)
result = await query.query(state=state)
assert [plugin.id for plugin in result] == ["Installed"]
assert result[0].installed is True
assert online_candidates.await_count == (1 if state == "all" else 0)
@pytest.mark.asyncio
async def test_market_query_keeps_local_candidates_when_online_markets_are_unavailable():
"""
远程市场不可用时保留本地仓库候选,避免故障屏蔽本地可安装插件。
"""
local_candidate = schemas.Plugin(
id="LocalCandidate",
repo_url="local://LocalCandidate",
)
query = PluginCatalogQuery(
installed_plugins=list,
local_plugins=list,
local_repo_plugins=lambda: [local_candidate],
online_candidates=AsyncMock(
side_effect=PluginMarketUnavailableError("索引读取失败")
),
process_plugins=lambda higher, base: higher + base,
identities=AsyncMock(return_value=[]),
free_threaded=lambda: False,
)
result = await query.query(state="market")
assert [plugin.id for plugin in result] == ["LocalCandidate"]
@pytest.mark.asyncio
async def test_market_query_keeps_uninstalled_runtime_plugins_when_online_markets_are_unavailable():
"""
远程市场不可用时保留本地未安装插件占位项。
"""
runtime_candidate = schemas.Plugin(id="RuntimeCandidate", installed=False)
query = PluginCatalogQuery(
installed_plugins=list,
local_plugins=lambda: [runtime_candidate],
local_repo_plugins=list,
online_candidates=AsyncMock(
side_effect=PluginMarketUnavailableError("索引读取失败")
),
process_plugins=lambda higher, base: higher + base,
identities=AsyncMock(return_value=[]),
free_threaded=lambda: False,
)
result = await query.query(state="market")
assert [plugin.id for plugin in result] == ["RuntimeCandidate"]
@pytest.mark.asyncio
@pytest.mark.parametrize("found", [False, True])
async def test_single_plugin_metadata_avoids_market_aggregation(monkeypatch, found):

View File

@@ -6,7 +6,8 @@ import asyncio
import json
import threading
from contextlib import asynccontextmanager, contextmanager
from unittest.mock import AsyncMock
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import pytest
@@ -56,8 +57,10 @@ async def test_failed_indexes_retry_after_short_cache_and_preserve_success_ttl(m
"""
requests.append(clock[0])
if clock[0] < 300:
return None if failure_status is None else (failure_status, "")
return 200, '{"Demo": {"version": "1.0.0"}}'
return helper._resolve_plugin_index_result(
None if failure_status is None else (failure_status, "")
)
return {"Demo": {"version": "1.0.0"}}
async def async_request(*args, **kwargs):
"""
@@ -103,13 +106,13 @@ async def test_force_refresh_bypasses_shared_negative_cache(monkeypatch):
"""
模拟同步入口首次连接仓库失败。
"""
return None
return helper._resolve_plugin_index_result(None)
async def async_request(*_args, **_kwargs):
"""
模拟强制重试时仓库已经恢复。
"""
return 200, '{"Demo": {"version": "2.0.0"}}'
return {"Demo": {"version": "2.0.0"}}
monkeypatch.setattr(helper, SYNC_INDEX_REQUEST, sync_request)
request = AsyncMock(side_effect=async_request)
@@ -199,8 +202,20 @@ class _SyncStreamResponse:
提供 requests 流式响应所需的最小测试契约。
"""
def __init__(self, content: bytes, content_length: str | None = None) -> None:
self.status_code = 200
def __init__(
self,
content: bytes,
content_length: str | None = None,
status_code: int = 200,
) -> None:
"""
保存本次离线流的正文、可选长度和 HTTP 状态。
:param content: 按字节读取的响应正文
:param content_length: 可选的 Content-Length 头值
:param status_code: 模拟响应状态码
"""
self.status_code = status_code
self.headers = {}
if content_length is not None:
self.headers["Content-Length"] = content_length
@@ -222,8 +237,20 @@ class _AsyncStreamResponse:
提供 httpx 流式响应所需的最小测试契约。
"""
def __init__(self, content: bytes, content_length: str | None = None) -> None:
self.status_code = 200
def __init__(
self,
content: bytes,
content_length: str | None = None,
status_code: int = 200,
) -> None:
"""
保存本次离线异步流的正文、可选长度和 HTTP 状态。
:param content: 按字节读取的响应正文
:param content_length: 可选的 Content-Length 头值
:param status_code: 模拟响应状态码
"""
self.status_code = status_code
self.headers = {}
if content_length is not None:
self.headers["Content-Length"] = content_length
@@ -271,7 +298,7 @@ def test_plugin_index_request_uses_sync_stream_transport(monkeypatch) -> None:
headers={"Accept": "application/json"},
)
assert result == (200, '{"DemoPlugin":{"version":"1.0.0"}}')
assert result == {"DemoPlugin": {"version": "1.0.0"}}
assert calls[0][0]["headers"] == {"Accept": "application/json"}
assert calls[0][2] is True
@@ -308,11 +335,113 @@ async def test_plugin_index_request_uses_async_stream_transport(monkeypatch) ->
headers={"Accept": "application/json"},
)
assert result == (200, '{"DemoPlugin":{"version":"1.0.0"}}')
assert result == {"DemoPlugin": {"version": "1.0.0"}}
assert calls[0][0]["headers"] == {"Accept": "application/json"}
assert calls[0][2] is True
@pytest.mark.asyncio
@pytest.mark.parametrize("mode", ["sync", "async"])
@pytest.mark.parametrize(
("mirror", "origin_status", "expected_error"),
[
pytest.param((200, b"{}"), 200, None, id="valid-empty-mirror"),
pytest.param((404, b"<html>not found</html>"), 200, None, id="mirror-404"),
pytest.param((503, b"unavailable"), 200, None, id="mirror-503"),
pytest.param((200, b"<html>anti-bot page</html>"), 200, None, id="mirror-html"),
pytest.param((200, b"[]"), 200, None, id="mirror-json-array"),
pytest.param((200, b"x" * (PLUGIN_INDEX_MAX_BYTES + 1)), 200, None, id="mirror-oversize"),
pytest.param((404, b"not found"), 404, None, id="origin-404"),
pytest.param((404, b"not found"), 503, "HTTP 503", id="origin-503"),
pytest.param((404, b"not found"), None, "连接失败", id="origin-unreachable"),
],
)
async def test_plugin_index_fallback_checks_response_before_accepting_it(
monkeypatch,
mode: str,
mirror: tuple[int, bytes],
origin_status: int | None,
expected_error: str | None,
) -> None:
"""
只有可解析索引或原始出口的 404 可以结束降级;镜像失败后仍保留原始出口的结果。
"""
settings = {
"GITHUB_PROXY": "https://mirror.example",
"PROXY_HOST": None,
"PROXY": None,
}
monkeypatch.setattr(
plugin_client_module,
"get_runtime_setting",
lambda key, default=None: settings.get(key, default),
)
calls: list[str] = []
index_url = "https://raw.githubusercontent.com/example/repo/main/package.v3.json"
mirror_url = f"https://mirror.example/{index_url}"
def response_for(url: str) -> tuple[int, bytes] | None:
"""
记录出口顺序并按实际请求地址选择离线响应。
"""
calls.append(url)
if url == mirror_url:
return mirror
assert url == index_url
if origin_status is None:
return None
return origin_status, b'{"DemoPlugin": {"version": "1.0.0"}}'
@contextmanager
def sync_stream(*, url: str, raise_exception: bool):
"""
用离线响应替代同步出站流。
"""
assert raise_exception is True
raw = response_for(url)
yield _SyncStreamResponse(raw[1], status_code=raw[0]) if raw else None
@asynccontextmanager
async def async_stream(*, url: str, raise_exception: bool):
"""
用离线响应替代异步出站流。
"""
assert raise_exception is True
raw = response_for(url)
yield _AsyncStreamResponse(raw[1], status_code=raw[0]) if raw else None
monkeypatch.setattr(
plugin_client_module, "RequestUtils", Mock(return_value=SimpleNamespace(get_stream=sync_stream))
)
monkeypatch.setattr(
plugin_client_module, "AsyncRequestUtils", Mock(return_value=SimpleNamespace(get_stream=async_stream))
)
transport = PluginMarketTransport()
async def fetch():
"""
通过实际传输入口执行同步或异步索引读取。
"""
if mode == "sync":
return transport._fetch_plugin_index_sync(index_url, None)
return await transport._fetch_plugin_index_async(index_url, None)
if expected_error:
with pytest.raises(RuntimeError, match=expected_error):
await fetch()
elif mirror == (200, b"{}"):
assert await fetch() == {}
elif origin_status == 404:
assert await fetch() is None
else:
assert await fetch() == {"DemoPlugin": {"version": "1.0.0"}}
if mirror == (200, b"{}"):
assert calls == [mirror_url]
else:
assert calls == [mirror_url, index_url]
@pytest.mark.asyncio
async def test_sync_and_async_plugin_indexes_share_request_and_result(
monkeypatch,
@@ -322,7 +451,7 @@ async def test_sync_and_async_plugin_indexes_share_request_and_result(
"""
helper = PluginMarketTransport()
repo_url = "https://github.com/policy-owner/policy-repository"
response = (200, '{"DemoPlugin": {"version": "1.2.3"}}')
response = {"DemoPlugin": {"version": "1.2.3"}}
sync_requests: list[tuple[str, dict]] = []
async_requests: list[tuple[str, dict]] = []
@@ -380,7 +509,7 @@ async def test_market_read_warms_source_inventory_cache(monkeypatch) -> None:
async def request(_url: str, *, headers: dict):
nonlocal requests
requests += 1
return 200, '{"DemoPlugin": {"version": "1.2.3"}}'
return {"DemoPlugin": {"version": "1.2.3"}}
monkeypatch.setattr(
helper,
@@ -411,7 +540,7 @@ def test_sync_force_refresh_bypasses_index_cache(
def request(_url: str, *, headers: dict):
nonlocal requests
requests += 1
return 200, f'{{"DemoPlugin": {{"version": "{version}"}}}}'
return {"DemoPlugin": {"version": version}}
monkeypatch.setattr(
helper,
@@ -451,7 +580,7 @@ async def test_async_force_refresh_bypasses_index_cache(
async def request(_url: str, *, headers: dict):
nonlocal requests
requests += 1
return 200, f'{{"DemoPlugin": {{"version": "{version}"}}}}'
return {"DemoPlugin": {"version": version}}
monkeypatch.setattr(
helper,
@@ -487,7 +616,7 @@ async def test_absent_plugin_generation_is_cached(monkeypatch) -> None:
async def request(_url: str, *, headers: dict):
nonlocal requests
requests += 1
return 404, ""
return None
monkeypatch.setattr(
helper,
@@ -516,7 +645,7 @@ async def test_index_cache_retains_multi_market_generation_working_set(
async def request(_url: str, *, headers: dict):
nonlocal requests
requests += 1
return 200, '{"DemoPlugin": {"version": "1.0.0"}}'
return {"DemoPlugin": {"version": "1.0.0"}}
monkeypatch.setattr(
helper,
@@ -827,7 +956,7 @@ def test_plugin_index_result_preserves_read_state(
repo_url = f"https://github.com/policy-owner/policy-repository-{status_code}"
def request(_url: str, *, headers: dict):
return status_code, content
return helper._resolve_plugin_index_result((status_code, content))
monkeypatch.setattr(helper, SYNC_INDEX_REQUEST, request)
helper.get_plugin_index_result.cache_clear()
@@ -856,7 +985,7 @@ def test_plugin_index_result_raises_for_unusable_reads(
helper = PluginMarketTransport()
def request(_url: str, *, headers: dict):
return status_code, content
return helper._resolve_plugin_index_result((status_code, content))
monkeypatch.setattr(helper, SYNC_INDEX_REQUEST, request)
helper.get_plugin_index_result.cache_clear()
@@ -878,7 +1007,7 @@ def test_invalid_plugin_index_is_not_cached(monkeypatch) -> None:
def request(_url: str, *, headers: dict):
nonlocal requests
requests += 1
return 200, "not-json"
return helper._resolve_plugin_index_result((200, "not-json"))
monkeypatch.setattr(helper, SYNC_INDEX_REQUEST, request)
helper.get_plugin_index_result.cache_clear()
@@ -901,7 +1030,7 @@ async def test_async_plugin_index_result_preserves_absent_state(monkeypatch) ->
helper = PluginMarketTransport()
async def request(_url: str, *, headers: dict):
return 404, ""
return None
monkeypatch.setattr(
helper,
@@ -932,7 +1061,7 @@ async def test_async_plugin_index_failure_is_not_reported_as_background_task_err
previous_handler = loop.get_exception_handler()
async def request(_url: str, *, headers: dict):
return 200, "not-json"
return helper._resolve_plugin_index_result((200, "not-json"))
monkeypatch.setattr(helper, ASYNC_INDEX_REQUEST, request)
monkeypatch.setattr(
@@ -972,7 +1101,7 @@ async def test_async_plugin_index_requests_are_single_flight(monkeypatch) -> Non
requests += 1
started.set()
await release.wait()
return 200, '{"DemoPlugin": {"version": "1.2.3"}}'
return {"DemoPlugin": {"version": "1.2.3"}}
monkeypatch.setattr(helper, ASYNC_INDEX_REQUEST, request)
await helper.async_get_plugin_index_result.cache_clear()
@@ -1021,7 +1150,7 @@ async def test_async_plugin_index_requests_share_process_gate(monkeypatch) -> No
started.set()
await release.wait()
active -= 1
return 200, '{"DemoPlugin": {"version": "1.2.3"}}'
return {"DemoPlugin": {"version": "1.2.3"}}
monkeypatch.setattr(helper, ASYNC_INDEX_REQUEST, request)
await helper.async_get_plugin_index_result.cache_clear()