Files
mtusi2026lab2/app/db.py
T
2026-10-26 17:50:20 +03:00

39 lines
1.1 KiB
Python

"""Connection pool. The URL is never written to the log."""
import asyncio
import logging
import asyncpg
logger = logging.getLogger('messenger')
_ATTEMPTS = 40
async def open_pool(database_url: str) -> asyncpg.Pool:
delay = 0.5
last_type = 'error'
for attempt in range(1, _ATTEMPTS + 1):
pool = None
try:
pool = await asyncpg.create_pool(
database_url,
min_size=1,
max_size=10,
timeout=5,
command_timeout=5,
server_settings={'statement_timeout': '5000'},
)
async with pool.acquire() as conn:
await conn.execute('SELECT 1')
return pool
except Exception as exc:
last_type = type(exc).__name__
if pool is not None:
await pool.close()
if attempt == _ATTEMPTS:
break
logger.warning('database is not ready (%s), retrying', last_type)
await asyncio.sleep(delay)
delay = min(delay * 1.5, 2)
raise RuntimeError('database did not become reachable (%s)' % last_type)