Files
mtusi2026lab5/app/db.py
T

77 lines
1.9 KiB
Python

from __future__ import annotations
import asyncio
import os
from psycopg import AsyncConnection, OperationalError, waiting
from psycopg.rows import dict_row
from psycopg_pool import AsyncConnectionPool
DB_IO_TIMEOUT_SECONDS = float(
os.getenv("DB_IO_TIMEOUT_SECONDS", "3")
)
if DB_IO_TIMEOUT_SECONDS <= 0:
raise ValueError("DB_IO_TIMEOUT_SECONDS must be positive")
class DeadlineConnection(AsyncConnection):
async def wait(self, gen, interval=0.1):
try:
async with asyncio.timeout(DB_IO_TIMEOUT_SECONDS):
return await waiting.wait_async(
gen,
self.pgconn.socket,
interval=interval,
)
except TimeoutError:
await self.close()
raise OperationalError(
"PostgreSQL response deadline exceeded"
) from None
except asyncio.CancelledError:
await self.close()
raise
pool = AsyncConnectionPool(
conninfo="",
connection_class=DeadlineConnection,
kwargs={
"host": os.getenv("PGHOST", "postgres"),
"port": int(os.getenv("PGPORT", "5432")),
"dbname": os.getenv("PGDATABASE", "messenger"),
"user": os.getenv("PGUSER", "messenger"),
"password": os.environ.get("PGPASSWORD", ""),
"connect_timeout": 3,
"options": (
"-c statement_timeout=3000 "
"-c lock_timeout=2000 "
"-c idle_in_transaction_session_timeout=10000"
),
"row_factory": dict_row,
},
min_size=1,
max_size=5,
timeout=3,
max_waiting=20,
open=False,
check=AsyncConnectionPool.check_connection,
)
async def open_db() -> None:
await pool.open(wait=True, timeout=10)
async def close_db() -> None:
await pool.close()
async def check_db() -> None:
async with pool.connection() as conn:
await conn.execute("SELECT 1")