From 0165e35e4020592853c96e51483496950d15432d Mon Sep 17 00:00:00 2001 From: RejectModders <142326052+RejectModders@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:39:22 -0600 Subject: [PATCH] fix(database): retry on the same pool after a lost connection Each lost connection built another pool of ten connections and then ran the query on the old one anyway. The pool replaces a lost connection itself, so one more try is enough. --- .basedpyright/baseline.json | 48 --------------------------- CHANGELOG.md | 5 +++ backend/base_pg.py | 65 +++++++------------------------------ tests/test_database_tls.py | 37 ++++++++++++++++----- 4 files changed, 44 insertions(+), 111 deletions(-) diff --git a/.basedpyright/baseline.json b/.basedpyright/baseline.json index 83724a6..1e94148 100644 --- a/.basedpyright/baseline.json +++ b/.basedpyright/baseline.json @@ -1,14 +1,6 @@ { "files": { "./backend/base_db.py": [ - { - "code": "reportImportCycles", - "range": { - "startColumn": 0, - "endColumn": 0, - "lineCount": 1 - } - }, { "code": "reportAny", "range": { @@ -147,14 +139,6 @@ "lineCount": 1 } }, - { - "code": "reportAny", - "range": { - "startColumn": 14, - "endColumn": 35, - "lineCount": 1 - } - }, { "code": "reportExplicitAny", "range": { @@ -211,38 +195,6 @@ "lineCount": 1 } }, - { - "code": "reportImplicitStringConcatenation", - "range": { - "startColumn": 16, - "endColumn": 61, - "lineCount": 2 - } - }, - { - "code": "reportImplicitStringConcatenation", - "range": { - "startColumn": 16, - "endColumn": 69, - "lineCount": 2 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 12, - "endColumn": 18, - "lineCount": 1 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 19, - "endColumn": 25, - "lineCount": 1 - } - }, { "code": "reportAny", "range": { diff --git a/CHANGELOG.md b/CHANGELOG.md index 9508c6b..5c95f80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ The format follows [Keep a Changelog](https://keepachangelog.com/). - The license is stated as GPL-3.0-only, in `pyproject.toml` and the README. +### Fixed + +- A lost database connection is retried on the same pool. Before, each + failure opened another pool of ten connections. + ## 1.0.2 - 2026-11-29 ### Changed diff --git a/backend/base_pg.py b/backend/base_pg.py index f0506cc..91dbf1f 100644 --- a/backend/base_pg.py +++ b/backend/base_pg.py @@ -7,8 +7,6 @@ from asyncpg import ConnectionDoesNotExistError, Pool, connection, protocol -from backend.base_db import BaseData - if TYPE_CHECKING: from asyncpg import Connection @@ -18,34 +16,13 @@ class BasePool(Pool): - """ - A connection pool subclass that supports automatic reconnection - and method re-execution on connection failures. - """ + """A connection pool that tries a query again after a lost connection.""" def __init__(self, *args: Any, **kwargs: Any) -> None: - """ - Initialize the BasePool instance and store connection parameters. - - Parameters - ---------- - *args : Any - Positional arguments forwarded to the parent Pool class. - **kwargs : Any - Keyword arguments forwarded to the parent Pool class. - Expected keys include 'host', 'database', 'port', 'user', - 'password' and 'ssl'. - """ # asyncpg ships no types for the pool's arguments super().__init__(*args, **kwargs) # pyright: ignore[reportAny] - self.__host: str | None = kwargs.get("host") - self.__database: str | None = kwargs.get("database") - self.__port: int | None = kwargs.get("port") - self.__user: str | None = kwargs.get("user") - self.__password: str | None = kwargs.get("password") - self.__ssl: str | None = kwargs.get("ssl") - - async def __reconnect_execution( + + async def __retry_once( # pyright: ignore[reportAny] # no types self, method: Callable[..., Awaitable[Any]], *args: Any, @@ -54,8 +31,8 @@ async def __reconnect_execution( """|coro| Calls and awaits the method with passed args & kwargs. - If the database connection fails, it attempts to reconnect once - and re-executes the passed method. + If the connection was lost, it waits a moment and calls it once more. + The pool opens a new connection in place of the lost one. Parameters ---------- @@ -66,31 +43,11 @@ async def __reconnect_execution( return await method(*args, **kwargs) except ConnectionDoesNotExistError: _logger.warning( - f"Failed to connect to DB while executing method: {method.__name__}. " - "Attempting to create new pool connection..." + "Lost the database connection in %s. Trying once more.", + method.__name__, ) await asyncio.sleep(3) - BaseData.db_connection = await create_base_pool( - host=self.__host, - database=self.__database, - port=self.__port, - user=self.__user, - password=self.__password, - ssl=self.__ssl, - max_inactive_connection_lifetime=0, - ) - _logger.warning( - "Successfully created pool connection. " - f"Attempting to re-execute method: {method.__name__}" - ) - - result = await method(*args, **kwargs) - - _logger.warning( - f"Successfully re-executed method: {method.__name__}." - ) - - return result + return await method(*args, **kwargs) # pyright: ignore[reportAny] @override async def execute( @@ -113,7 +70,7 @@ async def execute( str The status string returned by the database. """ - return await self.__reconnect_execution( + return await self.__retry_once( super().execute, # pyright: ignore[reportUnknownArgumentType] query, *args, @@ -147,7 +104,7 @@ async def fetch( list[Any] A list of records fetched from the database. """ - return await self.__reconnect_execution( + return await self.__retry_once( super().fetch, # pyright: ignore[reportUnknownArgumentType] query, *args, @@ -182,7 +139,7 @@ async def fetchrow( Any A single record fetched from the database. """ - return await self.__reconnect_execution( + return await self.__retry_once( super().fetchrow, # pyright: ignore[reportUnknownArgumentType] query, *args, diff --git a/tests/test_database_tls.py b/tests/test_database_tls.py index feaed81..bd3405e 100644 --- a/tests/test_database_tls.py +++ b/tests/test_database_tls.py @@ -1,7 +1,7 @@ -"""The setting for encrypting the database connection reaches every pool.""" +"""The database pool: its encryption setting and a lost connection.""" from types import SimpleNamespace -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock import asyncpg # pyright: ignore[reportMissingTypeStubs] import discord.utils @@ -42,26 +42,45 @@ async def test_the_start_hands_the_setting_to_the_pool( assert pool.await_args.kwargs["ssl"] == passed -async def test_a_reconnect_keeps_the_setting( +async def test_a_lost_connection_is_retried_on_the_same_pool( monkeypatch: pytest.MonkeyPatch, ) -> None: + # The pool replaces a lost connection itself. A second pool per failure + # would soon use up the connections of the server. pool = create_base_pool(host="127.0.0.1", ssl="verify-full") query = AsyncMock( - side_effect=[asyncpg.ConnectionDoesNotExistError("gone"), None] + side_effect=[asyncpg.ConnectionDoesNotExistError("gone"), "row"] ) monkeypatch.setattr(asyncpg.Pool, "fetchrow", query) - again = AsyncMock(return_value=MagicMock()) - monkeypatch.setattr(backend.base_pg, "create_base_pool", again) + another = AsyncMock() + monkeypatch.setattr(backend.base_pg, "create_base_pool", another) # Only this module's wait, never the event loop's own. monkeypatch.setattr( backend.base_pg, "asyncio", SimpleNamespace(sleep=AsyncMock()) ) monkeypatch.setattr(BaseData, "db_connection", pool) - await pool.fetchrow("SELECT 1") + assert await pool.fetchrow("SELECT 1") == "row" - assert again.await_args is not None - assert again.await_args.kwargs["ssl"] == "verify-full" + assert query.await_count == 2 + another.assert_not_called() + assert BaseData.db_connection is pool + + +async def test_a_second_lost_connection_is_raised( + monkeypatch: pytest.MonkeyPatch, +) -> None: + pool = create_base_pool(host="127.0.0.1") + query = AsyncMock(side_effect=asyncpg.ConnectionDoesNotExistError("gone")) + monkeypatch.setattr(asyncpg.Pool, "execute", query) + monkeypatch.setattr( + backend.base_pg, "asyncio", SimpleNamespace(sleep=AsyncMock()) + ) + + with pytest.raises(asyncpg.ConnectionDoesNotExistError): + await pool.execute("SELECT 1") + + assert query.await_count == 2 async def test_a_misspelled_setting_stops_the_connection() -> None: