From d7c5955031e4a3c746fccc088634e305284fd40f Mon Sep 17 00:00:00 2001 From: Aqr-K <1210498076@qq.com> Date: Tue, 1 Sep 2026 20:23:49 -0400 Subject: [PATCH] =?UTF-8?q?fix(plugin):=20=E6=8F=92=E4=BB=B6=E8=87=AA?= =?UTF-8?q?=E6=9C=89=E6=95=B0=E6=8D=AE=E5=BA=93=E9=87=8A=E6=94=BE=E4=B8=8E?= =?UTF-8?q?=E9=94=80=E6=AF=81=E5=85=A8=E7=A8=8B=E5=AE=B9=E9=94=99=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E4=BF=AE=E6=AD=A3=E5=BB=BA=E8=A1=A8=E5=8E=BB=E9=87=8D?= =?UTF-8?q?=E4=B8=8E=20schema=20=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit release/destroy 统一经 _close_handle 先清线程局部会话再 dispose,两步失败都 只记日志:单个插件的连接池故障不再让 close_database 跳过宿主同步与异步引擎的 释放,release_all_databases 也逐插件隔离。按模型建表对 __table__ 去重,单表 继承的父子类一并声明时不再对同一张表建两次。 卸载编排先删插件数据、后停插件,停机钩子里的 get_database() 会把刚销毁的库 重新建出来:注册表记下已销毁的插件标识,其后的 release 改为再次销毁并清除 标记,ensure 则撤销标记,宿主编排代码不动。PostgreSQL schema 名在归一改写过 标识或超长时追加插件标识哈希并截到 63 字节,My-Plugin、My_Plugin 与 my_plugin 不再折叠到同一个 schema 而在卸载时互相 DROP。 start 的失败分支释放已经建立、却进不了运行态的句柄,整体停止把只登记在 _classes 里的插件一并释放。声明的迁移目录不存在时在建句柄之前抛 FileNotFoundError,不再留下空库;SQLite 迁移 URL 改由引擎渲染; _get_sqlite_engine 的连接参数下沉到实际使用它的异步分支。 --- app/db/engine.py | 20 +- app/db/plugin/container.py | 5 +- app/db/plugin/locator.py | 32 +- app/db/plugin/migration.py | 5 +- app/db/plugin/registry.py | 84 +++-- app/plugins/__init__.py | 4 +- app/runtime/extensions/plugin/database.py | 8 +- app/runtime/extensions/plugin/lifecycle.py | 6 +- docs/rules/10-data-and-persistent.md | 40 ++- tests/test_db_plugin_framework.py | 357 ++++++++++++++++++++- tests/test_plugin_database_hooks.py | 10 +- tests/test_plugin_database_lifecycle.py | 52 +++ 12 files changed, 558 insertions(+), 65 deletions(-) diff --git a/app/db/engine.py b/app/db/engine.py index ebf4ac619..2d74fac6c 100644 --- a/app/db/engine.py +++ b/app/db/engine.py @@ -167,16 +167,6 @@ def _get_sqlite_engine(is_async: bool = False, pooled: bool = False): """ 获取SQLite数据库引擎 """ - # 连接参数 - _connect_args = { - "timeout": get_runtime_setting("DB_TIMEOUT"), - } - # 允许部署侧注入驱动级参数(如 PgBouncer 事务模式下的 statement_cache_size) - _connect_args.update(get_runtime_setting("DB_CONNECT_ARGS") or {}) - # 启用 WAL 模式时的额外配置 - if get_runtime_setting("DB_WAL_ENABLE"): - _connect_args["check_same_thread"] = False - # 创建同步引擎 if not is_async: engine = build_sqlite_engine(get_runtime_setting("DB_SQLITE_URL")()) @@ -191,6 +181,16 @@ def _get_sqlite_engine(is_async: bool = False, pooled: bool = False): return engine else: + # 连接参数 + _connect_args = { + "timeout": get_runtime_setting("DB_TIMEOUT"), + } + # 允许部署侧注入驱动级参数(如 PgBouncer 事务模式下的 statement_cache_size) + _connect_args.update(get_runtime_setting("DB_CONNECT_ARGS") or {}) + # 启用 WAL 模式时的额外配置 + if get_runtime_setting("DB_WAL_ENABLE"): + _connect_args["check_same_thread"] = False + # 数据库参数,只能使用 NullPool _db_kwargs = { "url": get_runtime_setting("DB_SQLITE_URL")("aiosqlite"), diff --git a/app/db/plugin/container.py b/app/db/plugin/container.py index 7c1ac8e59..cf69c412a 100644 --- a/app/db/plugin/container.py +++ b/app/db/plugin/container.py @@ -6,8 +6,7 @@ from dataclasses import dataclass from pathlib import Path from sqlalchemy.engine import Engine -from sqlalchemy.orm import Session, sessionmaker -from sqlalchemy.orm import scoped_session as ScopedSessionRegistry +from sqlalchemy.orm import Session, scoped_session, sessionmaker __all__ = ["PluginDatabaseHandle"] @@ -25,7 +24,7 @@ class PluginDatabaseHandle: plugin_id: str engine: Engine session_factory: sessionmaker - scoped_session_factory: ScopedSessionRegistry + scoped_session_factory: scoped_session db_path: Path | None schema: str | None owns_engine: bool diff --git a/app/db/plugin/locator.py b/app/db/plugin/locator.py index 15686a353..c25cbdd8e 100644 --- a/app/db/plugin/locator.py +++ b/app/db/plugin/locator.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib from pathlib import Path from app.runtime.settings import get_runtime_setting @@ -16,6 +17,10 @@ __all__ = [ DATABASE_FILENAME = "plugin.db" # SQLite WAL 模式下与库文件同生共死的边车文件后缀 SIDECAR_SUFFIXES = ("-wal", "-shm") +# PostgreSQL 标识符上限 63 字节,超出部分会被静默截断成另一个 schema +SCHEMA_NAME_MAX_LENGTH = 63 +# 归一改写了插件标识时用于区分两个插件的哈希长度 +SCHEMA_NAME_HASH_LENGTH = 8 def sqlite_database_path(plugin_id: str) -> Path: @@ -44,12 +49,27 @@ def plugin_schema_name(plugin_id: str) -> str: """ 按插件标识拼出 PostgreSQL schema 名。 - 只保留小写字母、数字与下划线,避免插件标识中的字符逃逸成标识符片段。 + 只保留 ASCII 小写字母、数字与下划线,避免插件标识中的字符逃逸成标识符片段,也让 + 名字的字符数与字节数一致。归一是多对一的:``My-Plugin``、``My_Plugin`` 与 + ``my_plugin`` 会折叠到同一个名字,而卸载一个插件执行的是 ``DROP SCHEMA ... + CASCADE``,折叠意味着删掉另一个插件的全部数据。 + 因此只要归一改写过标识,就追加插件标识的哈希把它们重新分开;超长标识同样追加哈希 + 再截断,截断本身也是一次折叠。 :param plugin_id: 插件标识 - :return: 合法的 schema 名 + :return: 合法且与插件标识一一对应的 schema 名 """ - raw = f"plugin_{plugin_id}".lower() - return "".join( - character if character.isalnum() or character == "_" else "_" - for character in raw + raw = f"plugin_{plugin_id}" + sanitized = "".join( + character + if (character.isascii() and character.isalnum()) or character == "_" + else "_" + for character in raw.lower() ) + if sanitized == raw and len(sanitized) <= SCHEMA_NAME_MAX_LENGTH: + return sanitized + digest = hashlib.sha1( + plugin_id.encode("utf-8"), + usedforsecurity=False, + ).hexdigest()[:SCHEMA_NAME_HASH_LENGTH] + suffix = f"_{digest}" + return f"{sanitized[:SCHEMA_NAME_MAX_LENGTH - len(suffix)]}{suffix}" diff --git a/app/db/plugin/migration.py b/app/db/plugin/migration.py index bbfe91f5b..810232d59 100644 --- a/app/db/plugin/migration.py +++ b/app/db/plugin/migration.py @@ -28,7 +28,10 @@ def run_migrations(handle: PluginDatabaseHandle, directory: Path) -> None: config.file_config = ConfigParser(interpolation=None) config.set_main_option("script_location", str(directory)) if handle.owns_engine: - config.set_main_option("sqlalchemy.url", f"sqlite:///{handle.db_path}") + config.set_main_option( + "sqlalchemy.url", + handle.engine.url.render_as_string(hide_password=False), + ) upgrade(config, "head") return with handle.engine.connect() as connection: diff --git a/app/db/plugin/registry.py b/app/db/plugin/registry.py index 1162ca26c..58ebdf6b9 100644 --- a/app/db/plugin/registry.py +++ b/app/db/plugin/registry.py @@ -31,11 +31,15 @@ __all__ = [ # 释放必须串行,否则同一插件会同时存在两个各持一份连接池的引擎 _lock = threading.RLock() _handles: dict[str, PluginDatabaseHandle] = {} +# 宿主的卸载编排先删插件数据、后停插件,插件的停机钩子取一次句柄就能把刚销毁的库重新 +# 建出来。销毁在此留下标记:其后的释放改为再次销毁,重新建库(ensure)则撤销标记 +_destroyed: set[str] = set() def _is_postgresql() -> bool: """判断宿主当前是否使用 PostgreSQL。""" - return str(get_runtime_setting("DB_TYPE")).lower() == "postgresql" + db_type: str = get_runtime_setting("DB_TYPE") + return db_type.lower() == "postgresql" def _build_handle(plugin_id: str) -> PluginDatabaseHandle: @@ -75,6 +79,25 @@ def _build_handle(plugin_id: str) -> PluginDatabaseHandle: ) +def _close_handle(handle: PluginDatabaseHandle) -> None: + """ + 先关闭线程局部会话再释放句柄独占的连接池。 + + 线程局部会话各自扣着一条连接,不先归还就 dispose,会让已经被移出注册表的句柄仍然 + 握着文件描述符。两步都是收尾操作,任一步失败只记日志:一个插件的连接池故障不得让 + 宿主引擎与其余插件的释放整体失败。 + :param handle: 数据库句柄 + """ + try: + handle.scoped_session_factory.remove() + except Exception as error: # noqa: BLE001 会话清理故障不得阻断连接池释放 + logger.warning(f"清理插件 {handle.plugin_id} 的线程局部会话失败:{error}") + try: + handle.dispose() + except Exception as error: # noqa: BLE001 单个插件的释放故障不得阻断其余释放 + logger.warning(f"释放插件 {handle.plugin_id} 的数据库连接失败:{error}") + + def get_database(plugin_id: str) -> PluginDatabaseHandle: """ 取插件的数据库句柄,句柄不存在时按需建立。 @@ -98,8 +121,9 @@ def _create_declared_tables(handle: PluginDatabaseHandle, models: Sequence[type] :param models: 插件声明的模型类 """ # 端口签名只承诺 type:__table__ 由 SQLAlchemy 声明式元类在类构造期动态挂载, - # 静态类型系统看不到这层映射 - tables = [model.__table__ for model in models] # type: ignore[attr-defined] + # 静态类型系统看不到这层映射。单表继承的父类与子类共享同一个 __table__,按对象去重 + # 后才不会把同一张表提交给 create_all 两次 + tables = list(dict.fromkeys(model.__table__ for model in models)) # type: ignore[attr-defined] for metadata in dict.fromkeys(table.metadata for table in tables): metadata.create_all( bind=handle.engine, @@ -120,8 +144,15 @@ def ensure_database( :param plugin_id: 插件标识 :param models: 插件声明的模型类 :param migrations: 插件声明的 Alembic 迁移目录 + :raise FileNotFoundError: 声明的迁移目录不存在 """ + with _lock: + _destroyed.discard(plugin_id) if migrations is not None: + # 目录校验必须早于建句柄:alembic 找不到 script_location 时抛错,而句柄已经把 + # 库文件建了出来,插件下次启动面对的是一个既没有表、也没有版本号的空库 + if not migrations.is_dir(): + raise FileNotFoundError(f"插件 {plugin_id} 声明的迁移目录不存在:{migrations}") # 迁移目录同时描述建表与后续版本演进,与按模型建表会争夺同一批表,故优先且互斥。 # alembic 只在插件真的声明了迁移目录时才需要,在函数内导入可让宿主与只声明模型的 # 插件不为它付出导入代价 @@ -138,21 +169,29 @@ def release_database(plugin_id: str) -> None: 释放插件的数据库连接,保留全部数据。 只 dispose 句柄自己拥有的引擎;PostgreSQL 下句柄只是宿主引擎的外观,这里不会、 - 也不能触碰宿主连接池。 + 也不能触碰宿主连接池。插件的数据库已被销毁、却又在停机钩子里重新取过句柄时,本次 + 释放改为再次销毁:那份重新建出来的库不属于任何仍然存在的插件,此后再无人回收。 :param plugin_id: 插件标识 """ with _lock: handle = _handles.pop(plugin_id, None) + was_destroyed = plugin_id in _destroyed + _destroyed.discard(plugin_id) if handle is not None: - handle.dispose() + _close_handle(handle) + if was_destroyed: + _remove_storage(plugin_id, handle) def release_all_databases() -> None: """释放全部插件的数据库连接,供进程关停使用。""" with _lock: - plugin_ids = list(_handles) + plugin_ids = list(dict.fromkeys((*_handles, *_destroyed))) for plugin_id in plugin_ids: - release_database(plugin_id) + try: + release_database(plugin_id) + except Exception as error: # noqa: BLE001 单个插件的故障不得阻断宿主引擎释放 + logger.warning(f"释放插件 {plugin_id} 的数据库失败:{error}") def _drop_schema(plugin_id: str, schema: str) -> None: @@ -168,20 +207,12 @@ def _drop_schema(plugin_id: str, schema: str) -> None: logger.error(f"销毁插件 {plugin_id} 的数据库 schema {schema} 失败:{error}") -def destroy_database(plugin_id: str) -> None: +def _remove_storage(plugin_id: str, handle: PluginDatabaseHandle | None) -> None: """ - 销毁插件的数据库:SQLite 删除库文件与 -wal/-shm 边车,PostgreSQL 丢弃对应 schema。 - - 不可逆,调用方必须确认处在「删除插件数据」而非「停止插件」的路径上。失败只记日志: - 删除数据是一次收尾操作,把文件系统或数据库的清理故障升级成异常,只会让已经删掉的 - 宿主数据与仍然存在的插件库停在不一致的中间态。 + 删除插件数据库的持久载体:SQLite 删库文件与边车,PostgreSQL 丢弃 schema。 :param plugin_id: 插件标识 + :param handle: 已释放的句柄,为空时按插件标识重新推导载体位置 """ - with _lock: - handle = _handles.pop(plugin_id, None) - if handle is not None: - handle.dispose() - if _is_postgresql(): # 句柄存在时 schema 必非空(PostgreSQL 分支总会填充);句柄已释放则重新按插件标识 # 推导,两种取值路径的类型都靠 or 收窄为确定的 str,不引入运行期新分支 @@ -195,3 +226,20 @@ def destroy_database(plugin_id: str) -> None: candidate.unlink(missing_ok=True) except OSError as error: logger.warning(f"删除插件 {plugin_id} 的数据库文件 {candidate} 失败:{error}") + + +def destroy_database(plugin_id: str) -> None: + """ + 销毁插件的数据库:SQLite 删除库文件与 -wal/-shm 边车,PostgreSQL 丢弃对应 schema。 + + 不可逆,调用方必须确认处在「删除插件数据」而非「停止插件」的路径上。失败只记日志: + 删除数据是一次收尾操作,把文件系统或数据库的清理故障升级成异常,只会让已经删掉的 + 宿主数据与仍然存在的插件库停在不一致的中间态。 + :param plugin_id: 插件标识 + """ + with _lock: + handle = _handles.pop(plugin_id, None) + _destroyed.add(plugin_id) + if handle is not None: + _close_handle(handle) + _remove_storage(plugin_id, handle) diff --git a/app/plugins/__init__.py b/app/plugins/__init__.py index 8bc7d4efb..5f3d9111e 100644 --- a/app/plugins/__init__.py +++ b/app/plugins/__init__.py @@ -255,7 +255,9 @@ class _PluginBase(metaclass=ABCMeta): def get_database_migrations(self) -> Optional[Union[str, Path]]: """ 声明插件自有数据库的 Alembic 迁移脚本目录 - 目录须符合 Alembic script_location 布局 + 目录须符合 Alembic script_location 布局,且必须是绝对路径 + (相对路径按宿主进程的当前工作目录解析,插件无法预期它指向哪里, + 建议用 Path(__file__).parent / "migrations" 之类的写法取得) 声明后插件启动时执行 alembic upgrade head,不再按 get_database_models() 建表。 PostgreSQL 下迁移脚本的 env.py 必须从 context.config.attributes["connection"] diff --git a/app/runtime/extensions/plugin/database.py b/app/runtime/extensions/plugin/database.py index fd5d203db..d9f5e9de7 100644 --- a/app/runtime/extensions/plugin/database.py +++ b/app/runtime/extensions/plugin/database.py @@ -42,10 +42,10 @@ class PluginDatabase: self._destroy = destroy def ensure( - self, - plugin_id: str, - models: Sequence[type], - migrations: Path | None, + self, + plugin_id: str, + models: Sequence[type], + migrations: Path | None, ) -> None: """按插件声明建立自有数据库,两项声明都为空时不建库。""" self._ensure(plugin_id, models, migrations) diff --git a/app/runtime/extensions/plugin/lifecycle.py b/app/runtime/extensions/plugin/lifecycle.py index 91495fb3b..ebd4e8748 100644 --- a/app/runtime/extensions/plugin/lifecycle.py +++ b/app/runtime/extensions/plugin/lifecycle.py @@ -142,6 +142,9 @@ class PluginLifecycle: status = PluginRuntimeStatus.LOAD_FAILED self._runtime_status_writer(plugin_id or current_id, status) results[plugin_id or current_id] = status + # 建库发生在进入运行态之前:失败的插件不会出现在 _running 里,卸载路径 + # 因此够不到它,句柄只能在这里释放 + self._release_databases((current_id,)) self._logger.error( f"加载插件 {current_id} 出错:{error} - {traceback.format_exc()}" ) @@ -326,7 +329,8 @@ class PluginLifecycle: self._quiesced_hooks.pop(runtime_id, None) self._release_databases((runtime_id,)) else: - released_ids = tuple(self._running) + # 启动中途失败的插件只登记在 _classes 里,漏掉它就漏掉它的连接池 + released_ids = tuple(dict.fromkeys((*self._running, *self._classes))) self._classes.clear() self._running.clear() self._quiesced_hooks.clear() diff --git a/docs/rules/10-data-and-persistent.md b/docs/rules/10-data-and-persistent.md index 5299a7d9d..485600a49 100644 --- a/docs/rules/10-data-and-persistent.md +++ b/docs/rules/10-data-and-persistent.md @@ -247,28 +247,50 @@ oper.delete(sid=1) # Delete by key Plugins that need SQL storage beyond `save_data`/`get_data` own an isolated database rather than a table inside the host database. The framework lives in `app/db/plugin/`: SQLite deploys one file per plugin at -`PLUGIN_DATA_PATH//plugin.db`; PostgreSQL deploys one schema -`plugin_` that reuses the host engine via `schema_translate_map`. +`PLUGIN_DATA_PATH//plugin.db`; PostgreSQL deploys one schema that +reuses the host engine via `schema_translate_map`. The schema name is +`plugin_` when the plugin id already consists of lowercase ASCII +alphanumerics and underscores and the result fits in 63 bytes; otherwise the +sanitized name carries an 8-hex-character suffix derived from the plugin id, +so `My-Plugin`, `My_Plugin` and `my_plugin` never share one schema — uninstall +issues `DROP SCHEMA ... CASCADE` and a shared name would delete another +plugin's data. A plugin declares its schema with `get_database_models()` and/or `get_database_migrations()`. The host pulls both hooks once, right after `init_plugin()` returns, and creates nothing when both are empty — most plugins never pay for this framework. A declared migrations directory takes -precedence over declared models and is applied with `alembic upgrade head`. +precedence over declared models and is applied with `alembic upgrade head`; +it must be an absolute, existing directory — `ensure` raises +`FileNotFoundError` before creating anything rather than leaving behind a +database with neither tables nor a version stamp. Models must inherit `app.sdk.database.plugin_declarative_base()`, which mints a fresh `MetaData` per call so a plugin's tables never collide with `app.db.base.Base.metadata` or with another plugin's same-named tables. At runtime, `_PluginBase.get_database()` returns a `PluginDatabaseHandle` for -opening sessions against the plugin's own engine. +opening sessions against the plugin's own engine. Declaring nothing is not the +same as never having a database: `get_database()` creates the SQLite file (or +the PostgreSQL schema) on first call, so a plugin that only runs raw SQL still +gets an isolated database. Lifecycle is strictly ensure/release/destroy: plugin start calls `ensure` after `init_plugin()`; stop, reload and remove call `release` only, which -disposes the connection pool but never touches data. Only resetting a -plugin's data or uninstalling a clone/virtual instance calls `destroy` -(delete the SQLite file and its `-wal`/`-shm` sidecars, or `DROP SCHEMA -... CASCADE`). Stopping or uninstalling an ordinary plugin never destroys its -database, mirroring the existing `plugindata` retention semantics. +closes the handle's thread-local sessions and never touches data. `release` +disposes the connection pool only under SQLite, where the handle owns its +engine; under PostgreSQL the handle is a view over the host engine, and +disposing it would take the host and every other plugin down with it. Only +resetting a plugin's data or uninstalling a clone/virtual instance calls +`destroy` (delete the SQLite file and its `-wal`/`-shm` sidecars, or `DROP +SCHEMA ... CASCADE`). Stopping or uninstalling an ordinary plugin never +destroys its database, mirroring the existing `plugindata` retention +semantics. + +Uninstall destroys the database before the plugin is stopped, so a stop hook +calling `get_database()` recreates it. A destroyed plugin id is remembered +until its next `release` — which destroys the recreated database instead of +merely releasing it — or its next `ensure`, which clears the mark because the +plugin is legitimately starting again. `db_query` / `db_update` keep their existing automatic-Session fallback bound to the **host** `ScopedSession()`; they are not aware of plugin-owned diff --git a/tests/test_db_plugin_framework.py b/tests/test_db_plugin_framework.py index 947ed5f34..ccdcee21a 100644 --- a/tests/test_db_plugin_framework.py +++ b/tests/test_db_plugin_framework.py @@ -2,31 +2,106 @@ from __future__ import annotations +import asyncio +import threading from pathlib import Path from unittest.mock import MagicMock import pytest from sqlalchemy import inspect as sa_inspect +from sqlalchemy import text from sqlalchemy.orm import Mapped, mapped_column +import app.db.engine as engine_module import app.db.plugin.locator as locator_module import app.db.plugin.migration as migration_module import app.db.plugin.registry as registry_module +import app.db.session as session_module from app.db.base import Base as HostBase from app.db.plugin.base import plugin_declarative_base -from app.db.plugin.locator import plugin_schema_name, sqlite_sidecar_paths +from app.db.plugin.container import PluginDatabaseHandle +from app.db.plugin.locator import ( + SCHEMA_NAME_MAX_LENGTH, + plugin_schema_name, + sqlite_sidecar_paths, +) @pytest.fixture(autouse=True) def _isolate_plugin_databases(): - """快照插件数据库句柄注册表,用例结束后释放残留句柄并还原快照。""" - snapshot = dict(registry_module._handles) + """快照插件数据库句柄与销毁标记,用例结束后释放残留句柄并还原快照。""" + handles = dict(registry_module._handles) + destroyed = set(registry_module._destroyed) registry_module._handles.clear() + registry_module._destroyed.clear() yield for plugin_id in list(registry_module._handles): registry_module.release_database(plugin_id) registry_module._handles.clear() - registry_module._handles.update(snapshot) + registry_module._handles.update(handles) + registry_module._destroyed.clear() + registry_module._destroyed.update(destroyed) + + +def _raise_dispose() -> None: + """模拟连接池释放失败。""" + raise RuntimeError("dispose failed") + + +def _write_migration_directory(root: Path) -> Path: + """ + 写出一个最小可用的 Alembic script_location,只含一条建表迁移。 + :param root: 承载迁移目录的父目录 + :return: 迁移目录路径 + """ + directory = root / "migrations" + (directory / "versions").mkdir(parents=True) + (directory / "env.py").write_text( + """from alembic import context +from sqlalchemy import create_engine + + +def _run(connection): + context.configure(connection=connection, target_metadata=None) + with context.begin_transaction(): + context.run_migrations() + + +injected = context.config.attributes.get("connection") +if injected is not None: + _run(injected) +else: + engine = create_engine(context.config.get_main_option("sqlalchemy.url")) + with engine.connect() as connection: + _run(connection) + engine.dispose() +""", + encoding="utf-8", + ) + (directory / "versions" / "0001_create_notes.py").write_text( + '''"""建立插件自有表。""" + +import sqlalchemy as sa +from alembic import op + +revision = "0001" +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + """建出插件声明的表。""" + op.create_table("notes", sa.Column("id", sa.Integer(), primary_key=True)) + + +def downgrade(): + """回退建表。""" + op.drop_table("notes") +''', + encoding="utf-8", + ) + return directory @pytest.fixture @@ -265,7 +340,12 @@ def test_postgresql_destroy_drops_the_schema_and_keeps_the_host_engine(postgresq host_engine.dispose.assert_not_called() -def test_declared_migrations_take_precedence_over_models(plugin_data_root, sqlite_backend, monkeypatch): +def test_declared_migrations_take_precedence_over_models( + plugin_data_root, + sqlite_backend, + monkeypatch, + tmp_path, +): """同时声明模型与迁移目录时优先走 alembic,且模型表不会被建出。""" calls: list[tuple[str, Path]] = [] monkeypatch.setattr( @@ -279,15 +359,39 @@ def test_declared_migrations_take_precedence_over_models(plugin_data_root, sqlit __tablename__ = "widgets" id: Mapped[int] = mapped_column(primary_key=True) - registry_module.ensure_database("demo", (Widget,), Path("migrations")) - assert calls == [("demo", Path("migrations"))] + directory = _write_migration_directory(tmp_path) + registry_module.ensure_database("demo", (Widget,), directory) + assert calls == [("demo", directory)] handle = registry_module.get_database("demo") assert "widgets" not in sa_inspect(handle.engine).get_table_names() def test_plugin_schema_name_sanitizes_the_plugin_id(): - """schema 名只保留小写字母、数字与下划线。""" - assert plugin_schema_name("Demo-Plugin.v2") == "plugin_demo_plugin_v2" + """schema 名只保留小写字母、数字与下划线,被改写过的标识再带上区分哈希。""" + schema = plugin_schema_name("Demo-Plugin.v2") + assert schema.startswith("plugin_demo_plugin_v2_") + assert schema.removeprefix("plugin_demo_plugin_v2_").isalnum() + + +def test_plugin_schema_name_keeps_an_already_legal_plugin_id_verbatim(): + """标识本身已是合法 schema 片段时不追加哈希。""" + assert plugin_schema_name("my_plugin") == "plugin_my_plugin" + + +def test_plugin_schema_name_separates_ids_that_normalize_to_the_same_text(): + """归一后同名的三个插件标识各自拿到不同 schema,卸载互不波及。""" + schemas = { + plugin_schema_name(plugin_id) + for plugin_id in ("My-Plugin", "My_Plugin", "my_plugin") + } + assert len(schemas) == 3 + + +def test_plugin_schema_name_fits_the_postgresql_identifier_limit(): + """超长插件标识被截断到 PostgreSQL 标识符上限以内,且仍带区分哈希。""" + schema = plugin_schema_name("p" * 200) + assert len(schema.encode("utf-8")) <= SCHEMA_NAME_MAX_LENGTH + assert plugin_schema_name("p" * 200) != plugin_schema_name("p" * 201) def test_sqlite_sidecar_paths_cover_wal_and_shm(): @@ -297,3 +401,238 @@ def test_sqlite_sidecar_paths_cover_wal_and_shm(): Path("/tmp/plugin.db-wal"), Path("/tmp/plugin.db-shm"), ) + + +def test_release_all_isolates_a_failing_plugin_dispose(plugin_data_root, sqlite_backend, monkeypatch): + """一个插件的连接池释放抛错,其余插件仍被释放,异常不向上传播。""" + handle_a = registry_module.get_database("plugin_a") + handle_b = registry_module.get_database("plugin_b") + calls: list[str] = [] + monkeypatch.setattr(handle_a.engine, "dispose", _raise_dispose) + monkeypatch.setattr(handle_b.engine, "dispose", lambda: calls.append("b")) + + registry_module.release_all_databases() + + assert calls == ["b"] + assert registry_module._handles == {} + + +def test_close_database_disposes_the_host_engine_when_a_plugin_dispose_fails( + plugin_data_root, + sqlite_backend, + monkeypatch, +): + """插件连接池释放抛错时,宿主同步引擎仍然被释放。""" + handle = registry_module.get_database("demo") + monkeypatch.setattr(handle.engine, "dispose", _raise_dispose) + disposed: list[str] = [] + host_engine = MagicMock(name="host_sync_engine") + host_engine.dispose.side_effect = lambda: disposed.append("host") + monkeypatch.setattr(engine_module, "peek_sync_engine", lambda: host_engine) + monkeypatch.setattr(engine_module, "peek_async_engine", lambda: None) + monkeypatch.setattr(session_module, "_pooled_async_engines", {}) + + asyncio.run(session_module.close_database()) + + assert disposed == ["host"] + + +def test_destroy_removes_the_database_file_even_when_dispose_fails( + plugin_data_root, + sqlite_backend, + monkeypatch, +): + """连接池释放抛错不得中断销毁,库文件照样被删除。""" + handle = registry_module.get_database("demo") + monkeypatch.setattr(handle.engine, "dispose", _raise_dispose) + + registry_module.destroy_database("demo") + + assert not handle.db_path.exists() + assert "demo" not in registry_module._handles + + +def test_single_table_inheritance_creates_the_shared_table_once(plugin_data_root, sqlite_backend): + """单表继承的父子类共享同一张表,一并声明只建一次,重复建库幂等。""" + base = plugin_declarative_base() + + class Node(base): + __tablename__ = "nodes" + __mapper_args__ = {"polymorphic_on": "kind", "polymorphic_identity": "node"} + id: Mapped[int] = mapped_column(primary_key=True) + kind: Mapped[str] = mapped_column() + + class Leaf(Node): + __mapper_args__ = {"polymorphic_identity": "leaf"} + + assert Leaf.__table__ is Node.__table__ + + registry_module.ensure_database("demo", (Node, Leaf)) + registry_module.ensure_database("demo", (Node, Leaf)) + + handle = registry_module.get_database("demo") + assert set(sa_inspect(handle.engine).get_table_names()) == {"nodes"} + + +def test_release_closes_the_thread_local_session(plugin_data_root, sqlite_backend): + """release 先清掉线程局部会话,句柄不再扣着已 dispose 引擎上的连接。""" + handle = registry_module.get_database("demo") + session = handle.scoped_session() + session.execute(text("SELECT 1")) + assert handle.scoped_session_factory.registry.has() is True + + registry_module.release_database("demo") + + assert handle.scoped_session_factory.registry.has() is False + + +def test_release_after_destroy_removes_a_database_revived_by_a_stop_hook( + plugin_data_root, + sqlite_backend, +): + """销毁后停机钩子取句柄让库文件复活,随后的 release 负责把它删掉并清除标记。""" + db_path = registry_module.get_database("demo").db_path + registry_module.destroy_database("demo") + assert not db_path.exists() + + revived = registry_module.get_database("demo") + assert revived.db_path.exists() + + registry_module.release_database("demo") + + assert not db_path.exists() + assert registry_module._destroyed == set() + + +def test_ensure_clears_the_destroyed_mark_so_a_restart_keeps_its_data( + plugin_data_root, + sqlite_backend, +): + """重新建库即撤销销毁标记,此后的 release 只释放连接、不再删库。""" + registry_module.get_database("demo") + registry_module.destroy_database("demo") + + registry_module.ensure_database("demo") + assert registry_module._destroyed == set() + + handle = registry_module.get_database("demo") + registry_module.release_database("demo") + + assert handle.db_path.exists() + + +def test_missing_migrations_directory_is_rejected_before_any_file_is_created( + plugin_data_root, + sqlite_backend, + tmp_path, +): + """迁移目录不存在时直接抛错,不留下空库文件,也不建插件数据目录。""" + with pytest.raises(FileNotFoundError): + registry_module.ensure_database("demo", (), tmp_path / "missing") + + assert "demo" not in registry_module._handles + assert not (plugin_data_root / "demo").exists() + + +def test_postgresql_handle_creates_the_plugin_schema(postgresql_backend): + """PostgreSQL 下建句柄先按插件 schema 执行 CREATE SCHEMA IF NOT EXISTS。""" + host_engine, _ = postgresql_backend + handle = registry_module.get_database("demo") + connection = host_engine.begin.return_value.__enter__.return_value + executed = [str(call.args[0]) for call in connection.execute.call_args_list] + assert f'CREATE SCHEMA IF NOT EXISTS "{handle.schema}"' in executed + + +def test_concurrent_get_database_builds_a_single_handle(plugin_data_root, sqlite_backend): + """八个线程同时取同一插件的句柄时只建出一个句柄,不会并存两份连接池。""" + thread_count = 8 + barrier = threading.Barrier(thread_count) + guard = threading.Lock() + handles: list[PluginDatabaseHandle] = [] + + def _acquire() -> None: + """在同一时刻取句柄并记录结果。""" + barrier.wait() + handle = registry_module.get_database("demo") + with guard: + handles.append(handle) + + threads = [threading.Thread(target=_acquire) for _ in range(thread_count)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert len(handles) == thread_count + assert all(handle is handles[0] for handle in handles) + assert list(registry_module._handles) == ["demo"] + + +def test_get_database_rebuilds_a_released_handle(plugin_data_root, sqlite_backend): + """release 之后再取句柄会重建出一个可用的新句柄。""" + first = registry_module.get_database("demo") + registry_module.release_database("demo") + + second = registry_module.get_database("demo") + + assert second is not first + session = second.session() + try: + assert session.execute(text("SELECT 1")).scalar() == 1 + finally: + session.close() + + +def test_get_database_rebuilds_a_destroyed_handle(plugin_data_root, sqlite_backend): + """destroy 之后再取句柄会重建库文件与新句柄。""" + first = registry_module.get_database("demo") + registry_module.destroy_database("demo") + + second = registry_module.get_database("demo") + + assert second is not first + assert second.db_path.exists() + session = second.session() + try: + assert session.execute(text("SELECT 1")).scalar() == 1 + finally: + session.close() + + +def test_run_migrations_upgrades_a_sqlite_plugin_database(plugin_data_root, sqlite_backend, tmp_path): + """声明迁移目录时按 alembic 建表并写入版本号,重复建库幂等。""" + directory = _write_migration_directory(tmp_path) + + registry_module.ensure_database("demo", (), directory) + + handle = registry_module.get_database("demo") + tables = set(sa_inspect(handle.engine).get_table_names()) + assert {"notes", "alembic_version"} <= tables + + registry_module.ensure_database("demo", (), directory) + + assert set(sa_inspect(handle.engine).get_table_names()) == tables + + +def test_run_migrations_routes_the_postgresql_connection_through_the_handle( + postgresql_backend, + monkeypatch, + tmp_path, +): + """PostgreSQL 下迁移复用句柄已限定 schema 的连接,并在结束后提交。""" + captured: dict[str, object] = {} + + def _record_upgrade(config, revision): + """记录 alembic 收到的连接与目标版本。""" + captured["connection"] = config.attributes.get("connection") + captured["revision"] = revision + + monkeypatch.setattr(migration_module, "upgrade", _record_upgrade) + handle = registry_module.get_database("demo") + + migration_module.run_migrations(handle, _write_migration_directory(tmp_path)) + + connection = handle.engine.connect.return_value.__enter__.return_value + assert captured["connection"] is connection + assert captured["revision"] == "head" + connection.commit.assert_called_once() diff --git a/tests/test_plugin_database_hooks.py b/tests/test_plugin_database_hooks.py index eb40ab606..d0aba9832 100644 --- a/tests/test_plugin_database_hooks.py +++ b/tests/test_plugin_database_hooks.py @@ -46,14 +46,18 @@ class _SamplePlugin(_PluginBase): @pytest.fixture(autouse=True) def _isolate_plugin_databases(): - """快照插件数据库句柄注册表,用例结束后释放残留句柄并还原快照。""" - snapshot = dict(registry_module._handles) + """快照插件数据库句柄与销毁标记,用例结束后释放残留句柄并还原快照。""" + handles = dict(registry_module._handles) + destroyed = set(registry_module._destroyed) registry_module._handles.clear() + registry_module._destroyed.clear() yield for plugin_id in list(registry_module._handles): registry_module.release_database(plugin_id) registry_module._handles.clear() - registry_module._handles.update(snapshot) + registry_module._handles.update(handles) + registry_module._destroyed.clear() + registry_module._destroyed.update(destroyed) @pytest.fixture diff --git a/tests/test_plugin_database_lifecycle.py b/tests/test_plugin_database_lifecycle.py index b4ffeed1f..3062c8291 100644 --- a/tests/test_plugin_database_lifecycle.py +++ b/tests/test_plugin_database_lifecycle.py @@ -402,3 +402,55 @@ def test_plugin_runtime_database_port_does_not_import_the_database_layer(): imported_modules.append(node.module) assert not any(module.startswith("app.db") for module in imported_modules) + + +def test_start_releases_the_database_of_a_plugin_that_failed_to_load(): + """建库失败的插件不会进入运行态,其句柄在失败分支就地释放。""" + calls: list[tuple] = [] + plugin_cls = _make_plugin_class("DemoPlugin") + + def _raise_ensure(plugin_id, _models, _migrations): + """模拟建库失败,但句柄可能已经建立。""" + calls.append(("ensure", plugin_id)) + raise RuntimeError("ensure failed") + + lifecycle = _build_lifecycle( + load_plugins=lambda *_a, **_kw: [plugin_cls], + installed_plugins=lambda: ["DemoPlugin"], + database=lambda: PluginDatabase( + ensure=_raise_ensure, + release=lambda plugin_id: calls.append(("release", plugin_id)), + ), + ) + + lifecycle.start("DemoPlugin") + + assert [call for call in calls if call[0] == "release"] == [("release", "DemoPlugin")] + assert "DemoPlugin" not in lifecycle._running + + +def test_stop_all_releases_plugins_that_never_reached_the_running_registry(): + """整体停止会释放启动中途失败、只登记在类注册表里的插件。""" + calls: list[tuple] = [] + plugin_cls = _make_plugin_class("DemoPlugin") + + def _raise_ensure(_plugin_id, _models, _migrations): + """模拟建库失败。""" + raise RuntimeError("ensure failed") + + lifecycle = _build_lifecycle( + load_plugins=lambda *_a, **_kw: [plugin_cls], + installed_plugins=lambda: ["DemoPlugin"], + database=lambda: PluginDatabase( + ensure=_raise_ensure, + release=lambda plugin_id: calls.append(("release", plugin_id)), + ), + ) + lifecycle.start() + assert "DemoPlugin" not in lifecycle._running + assert "DemoPlugin" in lifecycle._classes + calls.clear() + + lifecycle.stop() + + assert ("release", "DemoPlugin") in calls