From c6bed73848e8cdf9725418398b00a26c2c4d2fbc Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Sun, 12 Apr 2026 14:28:51 +0800 Subject: [PATCH] feat: add SQL connection pool configuration options and improve engine caching --- README.md | 4 ++++ app/control/account/backends/factory.py | 2 +- app/control/account/backends/sql.py | 26 ++++++++++++++----------- app/platform/config/backends/sql.py | 2 ++ docs/README.en.md | 4 ++++ 5 files changed, 26 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 2a0cb10a..a715b306 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,10 @@ docker compose up -d | `ACCOUNT_REDIS_URL` | `redis` 模式 Redis DSN | `""` | | `ACCOUNT_MYSQL_URL` | `mysql` 模式 SQLAlchemy DSN | `""` | | `ACCOUNT_POSTGRESQL_URL` | `postgresql` 模式 SQLAlchemy DSN | `""` | +| `ACCOUNT_SQL_POOL_SIZE` | SQL 连接池核心连接数 | `5` | +| `ACCOUNT_SQL_MAX_OVERFLOW` | SQL 连接池最大溢出连接数 | `10` | +| `ACCOUNT_SQL_POOL_TIMEOUT` | 等待连接池空闲连接的超时时间(秒) | `30` | +| `ACCOUNT_SQL_POOL_RECYCLE` | 连接最大复用时间(秒),超时后自动重连 | `1800` | ### 系统配置项 diff --git a/app/control/account/backends/factory.py b/app/control/account/backends/factory.py index b0424dfc..7b6f91ca 100644 --- a/app/control/account/backends/factory.py +++ b/app/control/account/backends/factory.py @@ -132,7 +132,7 @@ def _make_sql(dialect: str) -> AccountRepository: else: url = _get_env("ACCOUNT_POSTGRESQL_URL") engine = create_pgsql_engine(url) - return SqlAccountRepository(engine, dialect=dialect) + return SqlAccountRepository(engine, dialect=dialect, dispose_engine=False) __all__ = ["create_repository", "describe_repository_target", "get_repository_backend"] diff --git a/app/control/account/backends/sql.py b/app/control/account/backends/sql.py index f4eb62c9..d6a52379 100644 --- a/app/control/account/backends/sql.py +++ b/app/control/account/backends/sql.py @@ -138,8 +138,8 @@ _MYSQL_SSL_MODE_ALIASES: dict[str, str] = { } _ENGINE_CACHE_LOCK = Lock() -_ENGINE_CACHE: dict[tuple[str, str], AsyncEngine] = {} -_ENGINE_KEYS_BY_ID: dict[int, set[tuple[str, str]]] = {} +_ENGINE_CACHE: dict[tuple[str, str, str], AsyncEngine] = {} +_ENGINE_KEYS_BY_ID: dict[int, set[tuple[str, str, str]]] = {} def _normalize_sql_url(dialect: str, url: str) -> str: @@ -352,8 +352,8 @@ def _prepare_sql_url_and_connect_args( def _sql_engine_kwargs(connect_args: dict[str, Any] | None) -> dict[str, Any]: kwargs: dict[str, Any] = { - "pool_size": _get_env_int("ACCOUNT_SQL_POOL_SIZE", 1, minimum=1), - "max_overflow": _get_env_int("ACCOUNT_SQL_MAX_OVERFLOW", 0, minimum=0), + "pool_size": _get_env_int("ACCOUNT_SQL_POOL_SIZE", 5, minimum=1), + "max_overflow": _get_env_int("ACCOUNT_SQL_MAX_OVERFLOW", 10, minimum=0), "pool_timeout": _get_env_int("ACCOUNT_SQL_POOL_TIMEOUT", 30, minimum=1), "pool_recycle": _get_env_int("ACCOUNT_SQL_POOL_RECYCLE", 1800, minimum=0), "pool_pre_ping": True, @@ -365,7 +365,7 @@ def _sql_engine_kwargs(connect_args: dict[str, Any] | None) -> dict[str, Any]: def _get_or_create_engine( - cache_key: tuple[str, str], + cache_key: tuple[str, str, str], normalized_url: str, connect_args: dict[str, Any] | None, ) -> AsyncEngine: @@ -745,18 +745,22 @@ class SqlAccountRepository: await self._engine.dispose() +def _engine_cache_key(dialect: str, normalized_url: str, connect_args: dict[str, Any] | None) -> tuple[str, str, str]: + """Build a stable cache key from the normalized URL and connect args.""" + args_key = str(sorted(connect_args.items(), key=lambda kv: kv[0])) if connect_args else "" + return (dialect, normalized_url, args_key) + + def create_mysql_engine(url: str) -> AsyncEngine: """Create an async SQLAlchemy engine for MySQL.""" - raw_url = (url or "").strip() - normalized_url, connect_args = _prepare_sql_url_and_connect_args("mysql", raw_url) - return _get_or_create_engine(("mysql", raw_url), normalized_url, connect_args) + normalized_url, connect_args = _prepare_sql_url_and_connect_args("mysql", (url or "").strip()) + return _get_or_create_engine(_engine_cache_key("mysql", normalized_url, connect_args), normalized_url, connect_args) def create_pgsql_engine(url: str) -> AsyncEngine: """Create an async SQLAlchemy engine for PostgreSQL.""" - raw_url = (url or "").strip() - normalized_url, connect_args = _prepare_sql_url_and_connect_args("postgresql", raw_url) - return _get_or_create_engine(("postgresql", raw_url), normalized_url, connect_args) + normalized_url, connect_args = _prepare_sql_url_and_connect_args("postgresql", (url or "").strip()) + return _get_or_create_engine(_engine_cache_key("postgresql", normalized_url, connect_args), normalized_url, connect_args) __all__ = ["SqlAccountRepository", "create_mysql_engine", "create_pgsql_engine"] diff --git a/app/platform/config/backends/sql.py b/app/platform/config/backends/sql.py index 500d2ce6..e69843e7 100644 --- a/app/platform/config/backends/sql.py +++ b/app/platform/config/backends/sql.py @@ -125,4 +125,6 @@ class SqlConfigBackend(ConfigBackend): async def close(self) -> None: if self._dispose_engine: + from app.control.account.backends.sql import _evict_cached_engine + _evict_cached_engine(self._engine) await self._engine.dispose() diff --git a/docs/README.en.md b/docs/README.en.md index 4db9b716..828c83ec 100644 --- a/docs/README.en.md +++ b/docs/README.en.md @@ -179,6 +179,10 @@ docker compose up -d | `ACCOUNT_REDIS_URL` | Redis DSN for `redis` mode | `""` | | `ACCOUNT_MYSQL_URL` | SQLAlchemy DSN for `mysql` mode | `""` | | `ACCOUNT_POSTGRESQL_URL` | SQLAlchemy DSN for `postgresql` mode | `""` | +| `ACCOUNT_SQL_POOL_SIZE` | Core connection pool size for SQL backends | `5` | +| `ACCOUNT_SQL_MAX_OVERFLOW` | Maximum overflow connections above pool size | `10` | +| `ACCOUNT_SQL_POOL_TIMEOUT` | Seconds to wait for a free connection from the pool | `30` | +| `ACCOUNT_SQL_POOL_RECYCLE` | Max connection lifetime in seconds before reconnect | `1800` | ### System Configuration Groups