From 6dd644ee6151257f937ae61693a0d1134834dd9b Mon Sep 17 00:00:00 2001 From: zzz27578 <2950506809@qq.com> Date: Tue, 24 Nov 2026 18:23:39 +0800 Subject: [PATCH] fix(plugins): serialize updates and keep install sources current --- astrbot/core/star/star_manager.py | 53 +++++--- astrbot/dashboard/services/plugin_service.py | 100 ++++++++------- tests/test_plugin_manager.py | 123 +++++++++++++++++++ 3 files changed, 215 insertions(+), 61 deletions(-) diff --git a/astrbot/core/star/star_manager.py b/astrbot/core/star/star_manager.py index 57d80efb65..3331cd576a 100644 --- a/astrbot/core/star/star_manager.py +++ b/astrbot/core/star/star_manager.py @@ -12,11 +12,12 @@ import sys import tempfile import traceback -from collections.abc import Iterable +from collections.abc import Awaitable, Callable, Iterable from dataclasses import dataclass from enum import Enum, auto from pathlib import Path from types import ModuleType +from weakref import WeakValueDictionary import yaml from packaging.specifiers import InvalidSpecifier, SpecifierSet @@ -214,6 +215,9 @@ def __init__(self, context: Context, config: AstrBotConfig) -> None: """插件配置 Schema 文件名""" self._pm_lock = asyncio.Lock() """StarManager操作互斥锁""" + self._update_locks: WeakValueDictionary[Path, asyncio.Lock] = ( + WeakValueDictionary() + ) self.failed_plugin_dict = {} """加载失败插件的信息,用于后续可能的热重载""" @@ -1924,6 +1928,8 @@ async def update_plugin( proxy="", download_url: str = "", repo_url: str = "", + *, + on_files_replaced: Callable[[str], Awaitable[None]] | None = None, ) -> None: """Update and reload an installed plugin. @@ -1932,6 +1938,8 @@ async def update_plugin( proxy: Optional URL-prefix mirror for archive downloads. download_url: Optional direct plugin archive URL. repo_url: Repository locator selected by the update source. + on_files_replaced: Optional callback receiving the root directory name + after the updater replaces the files, even if loading later fails. Returns: None. @@ -1943,22 +1951,35 @@ async def update_plugin( plugin = self.context.get_registered_star(plugin_name) if not plugin: raise Exception("插件不存在。") - if plugin.reserved: - raise Exception("该插件是 AstrBot 保留插件,无法更新。") - - await self._updater.update( - plugin, - proxy=proxy, - download_url=download_url, - repo_url=repo_url, - ) - if plugin.root_dir_name: - plugin_dir_path = os.path.join(self.plugin_store_path, plugin.root_dir_name) - await self._ensure_plugin_requirements( - plugin_dir_path, - plugin_name, + root_dir_name = plugin.root_dir_name + if not root_dir_name: + raise ValueError(f"Plugin {plugin_name} has no root directory name.") + + plugin_path = Path(self.plugin_store_path) / root_dir_name + update_lock = self._update_locks.setdefault(plugin_path, asyncio.Lock()) + async with update_lock: + plugin = self.context.get_registered_star(plugin_name) + if not plugin or plugin.root_dir_name != root_dir_name: + raise Exception("插件不存在。") + if plugin.reserved: + raise Exception("该插件是 AstrBot 保留插件,无法更新。") + + await self._updater.update( + plugin, + proxy=proxy, + download_url=download_url, + repo_url=repo_url, ) - await self.reload(plugin_name) + try: + if on_files_replaced is not None: + await on_files_replaced(root_dir_name) + finally: + await self._ensure_plugin_requirements(str(plugin_path), plugin_name) + success, error = await self.reload(plugin_name) + if not success: + raise RuntimeError( + error or f"Failed to reload plugin {plugin_name} after update." + ) async def turn_off_plugin(self, plugin_name: str) -> None: """禁用一个插件。 diff --git a/astrbot/dashboard/services/plugin_service.py b/astrbot/dashboard/services/plugin_service.py index f880489995..008a9ff598 100644 --- a/astrbot/dashboard/services/plugin_service.py +++ b/astrbot/dashboard/services/plugin_service.py @@ -8,6 +8,7 @@ from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import datetime, timezone +from functools import partial from pathlib import Path from typing import Any @@ -109,6 +110,7 @@ def __init__( EventType.OnPluginErrorEvent: "插件报错时", } self._logo_cache: dict[str, str] = {} + self._install_source_lock = asyncio.Lock() @staticmethod def _payload(data: object) -> dict[str, Any]: @@ -1543,43 +1545,41 @@ async def bind_plugin_market_source(self, data: object) -> tuple[dict, str]: async def refresh_plugin_install_source_after_update( self, - plugin_name: str, + root_dir_name: str, update_info: dict[str, Any], ) -> None: - """Refresh stored source fields after a successful plugin update. + """Refresh the source for the installed files independently of reload. Args: - plugin_name: Installed plugin metadata name. + root_dir_name: Stable key for the installed plugin directory. update_info: Marketplace update information. """ - plugin = self.find_plugin_by_name(plugin_name) - if not plugin or not plugin.root_dir_name: - return - records = await self.get_plugin_install_sources() - record = records.get(plugin.root_dir_name) - if not isinstance(record, dict): - update_record = update_info.get("record") - if not isinstance(update_record, dict): - return - record = dict(update_record) - market_plugin = update_info.get("market_plugin") - if isinstance(market_plugin, dict): - market_plugin_id = self.get_market_plugin_id(market_plugin) - if market_plugin_id: - record["market_plugin_id"] = market_plugin_id - record["repo"] = str( - market_plugin.get("repo") or record.get("repo") or "" - ).strip() - record["download_url"] = str( - market_plugin.get("download_url") - or update_info.get("download_url") - or record.get("download_url") - or "" - ).strip() - record["root_dir_name"] = plugin.root_dir_name - record["updated_at"] = datetime.now(timezone.utc).isoformat() - records[plugin.root_dir_name] = record - await self.save_plugin_install_sources(records) + async with self._install_source_lock: + records = await self.get_plugin_install_sources() + record = records.get(root_dir_name) + if not isinstance(record, dict): + update_record = update_info.get("record") + if not isinstance(update_record, dict): + return + record = dict(update_record) + market_plugin = update_info.get("market_plugin") + if isinstance(market_plugin, dict): + market_plugin_id = self.get_market_plugin_id(market_plugin) + if market_plugin_id: + record["market_plugin_id"] = market_plugin_id + record["repo"] = str( + market_plugin.get("repo") or record.get("repo") or "" + ).strip() + record["download_url"] = str( + market_plugin.get("download_url") + or update_info.get("download_url") + or record.get("download_url") + or "" + ).strip() + record["root_dir_name"] = root_dir_name + record["updated_at"] = datetime.now(timezone.utc).isoformat() + records[root_dir_name] = record + await self.save_plugin_install_sources(records) async def install_plugin(self, data: object) -> tuple[dict, str]: self._ensure_not_demo() @@ -1802,15 +1802,19 @@ async def update_plugin(self, data: object) -> tuple[None, str]: download_url = str(update_info.get("download_url") or "").strip() repo_url = str(update_info.get("repo") or "").strip() logger.info(f"Updating plugin {plugin_name}") - await self.plugin_manager.update_plugin( - plugin_name, - proxy or "", - download_url=download_url, - repo_url=repo_url, - ) - await self.refresh_plugin_install_source_after_update(plugin_name, update_info) - await self.plugin_manager.reload(plugin_name) - await self.sync_skills_after_plugin_change() + try: + await self.plugin_manager.update_plugin( + plugin_name, + proxy or "", + download_url=download_url, + repo_url=repo_url, + on_files_replaced=partial( + self.refresh_plugin_install_source_after_update, + update_info=update_info, + ), + ) + finally: + await self.sync_skills_after_plugin_change() logger.info(f"Updated plugin {plugin_name} successfully.") return None, "更新成功。" @@ -1822,26 +1826,32 @@ async def update_all_plugins(self, data: object) -> tuple[dict, str]: if not isinstance(plugin_names, list) or not plugin_names: raise PluginServiceError("插件列表不能为空") + if any(not isinstance(name, str) for name in plugin_names): + raise PluginServiceError("插件名称必须是字符串") + plugin_names = list(dict.fromkeys(plugin_names)) results = [] sem = asyncio.Semaphore(PLUGIN_UPDATE_CONCURRENCY) + attempted_update = False async def _update_one(name: str): + nonlocal attempted_update async with sem: try: logger.info(f"Updating plugin {name} as part of a batch update.") update_info = await self.resolve_market_update_info(name) download_url = str(update_info.get("download_url") or "").strip() repo_url = str(update_info.get("repo") or "").strip() + attempted_update = True await self.plugin_manager.update_plugin( name, proxy, download_url=download_url, repo_url=repo_url, - ) - await self.refresh_plugin_install_source_after_update( - name, - update_info, + on_files_replaced=partial( + self.refresh_plugin_install_source_after_update, + update_info=update_info, + ), ) return {"name": name, "status": "ok", "message": "更新成功"} except PluginServiceError as exc: @@ -1887,7 +1897,7 @@ async def _update_one(name: str): results.append(result) failed = [result for result in results if result["status"] == "error"] - if len(failed) < len(results): + if attempted_update: await self.sync_skills_after_plugin_change() message = ( "批量更新完成,全部成功。" diff --git a/tests/test_plugin_manager.py b/tests/test_plugin_manager.py index a580eebdbd..adede4ad81 100644 --- a/tests/test_plugin_manager.py +++ b/tests/test_plugin_manager.py @@ -20,6 +20,7 @@ from astrbot.core.utils.astrbot_path import get_astrbot_system_tmp_path from astrbot.core.utils.pip_installer import PipInstallError from astrbot.core.utils.requirements_utils import MissingRequirementsPlan +from astrbot.dashboard.services.plugin_service import PluginService # --- Test Data & Helpers --- @@ -2089,6 +2090,128 @@ async def mock_update(plugin, proxy="", download_url="", repo_url=""): assert ("reload", TEST_PLUGIN_DIR) in events +@pytest.mark.asyncio +async def test_update_plugin_serializes_only_overlapping_plugin_updates( + plugin_manager_pm: PluginManager, monkeypatch +): + other_plugin = MockStar() + other_plugin.name = other_plugin.root_dir_name = "other_plugin" + cast(Any, plugin_manager_pm.context).stars.extend([MockStar(), other_plugin]) + first_reload_started = asyncio.Event() + allow_first_reload = asyncio.Event() + other_update_started = asyncio.Event() + versions = {} + loaded = [] + + async def update(plugin, *, proxy, download_url, repo_url): + versions[plugin.root_dir_name] = download_url + if plugin is other_plugin: + other_update_started.set() + + async def reload(name): + if name == TEST_PLUGIN_NAME and not first_reload_started.is_set(): + first_reload_started.set() + await allow_first_reload.wait() + loaded.append((name, versions[name])) + return True, None + + monkeypatch.setattr(plugin_manager_pm._updater, "update", update) + monkeypatch.setattr(plugin_manager_pm, "reload", reload) + + async with asyncio.timeout(5), asyncio.TaskGroup() as tasks: + tasks.create_task( + plugin_manager_pm.update_plugin(TEST_PLUGIN_NAME, download_url="first") + ) + await first_reload_started.wait() + tasks.create_task( + plugin_manager_pm.update_plugin(TEST_PLUGIN_NAME, download_url="second") + ) + tasks.create_task( + plugin_manager_pm.update_plugin(other_plugin.name, download_url="other") + ) + await other_update_started.wait() + allow_first_reload.set() + + assert loaded == [ + (other_plugin.name, "other"), + (TEST_PLUGIN_NAME, "first"), + (TEST_PLUGIN_NAME, "second"), + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("batch", [False, True]) +@pytest.mark.parametrize("download_fails", [False, True]) +async def test_update_plugin_persists_source_only_after_replacing_files( + plugin_manager_pm: PluginManager, monkeypatch, batch, download_fails +): + plugin_name = "demo_plugin" + plugin = MockStar() + plugin.name = plugin_name + stars = cast(Any, plugin_manager_pm.context).stars + stars.append(plugin) + service = PluginService(None, plugin_manager_pm) + old_source = { + "install_method": "market", + "market_plugin_id": "owner/old-plugin", + "repo": "https://github.com/owner/old-plugin", + "download_url": "https://example.com/old.zip", + "installed_at": "2026-01-01T00:00:00+00:00", + } + new_source = { + "market_plugin_id": "owner/new-plugin", + "repo": "https://github.com/owner/new-plugin", + "download_url": "https://example.com/new.zip", + } + write_sources = AsyncMock() + download = AsyncMock( + side_effect=RuntimeError("Download failed") if download_fails else None + ) + + async def reload(_name): + stars.clear() + return False, "Plugin initialization failed" + + reload_plugin = AsyncMock(side_effect=reload) + monkeypatch.setattr(plugin_manager_pm._updater, "update", download) + monkeypatch.setattr(plugin_manager_pm, "reload", reload_plugin) + monkeypatch.setattr(service, "sync_skills_after_plugin_change", AsyncMock()) + monkeypatch.setattr( + service, + "get_plugin_install_sources", + AsyncMock(return_value={TEST_PLUGIN_DIR: dict(old_source)}), + ) + monkeypatch.setattr(service, "save_plugin_install_sources", write_sources) + monkeypatch.setattr( + service, + "resolve_market_update_info", + AsyncMock(return_value={**new_source, "market_plugin": new_source}), + ) + + if batch: + data, _message = await service.update_all_plugins({"names": [plugin_name] * 2}) + assert [result["status"] for result in data["results"]] == ["error"] + else: + error = "Download failed" if download_fails else "Plugin initialization failed" + with pytest.raises(RuntimeError, match=error): + await service.update_plugin({"name": plugin_name}) + + download.assert_awaited_once() + if download_fails: + write_sources.assert_not_awaited() + reload_plugin.assert_not_awaited() + else: + reload_plugin.assert_awaited_once_with(plugin_name) + write_sources.assert_awaited_once() + record = write_sources.await_args.args[0][TEST_PLUGIN_DIR] + assert record == { + **old_source, + **new_source, + "root_dir_name": TEST_PLUGIN_DIR, + "updated_at": record["updated_at"], + } + + @pytest.mark.asyncio async def test_install_plugin_skips_dependency_install_when_no_requirements_missing( plugin_manager_pm: PluginManager, monkeypatch