Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 0 additions & 48 deletions .basedpyright/baseline.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
{
"files": {
"./backend/base_db.py": [
{
"code": "reportImportCycles",
"range": {
"startColumn": 0,
"endColumn": 0,
"lineCount": 1
}
},
{
"code": "reportAny",
"range": {
Expand Down Expand Up @@ -147,14 +139,6 @@
"lineCount": 1
}
},
{
"code": "reportAny",
"range": {
"startColumn": 14,
"endColumn": 35,
"lineCount": 1
}
},
{
"code": "reportExplicitAny",
"range": {
Expand Down Expand Up @@ -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": {
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
65 changes: 11 additions & 54 deletions backend/base_pg.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@

from asyncpg import ConnectionDoesNotExistError, Pool, connection, protocol

from backend.base_db import BaseData

if TYPE_CHECKING:
from asyncpg import Connection

Expand All @@ -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,
Expand All @@ -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
----------
Expand All @@ -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(
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
37 changes: 28 additions & 9 deletions tests/test_database_tls.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand Down