forked from mtusi2026/mtusi2026lab2
100 lines
3.1 KiB
Python
100 lines
3.1 KiB
Python
import asyncio
|
|
from contextlib import asynccontextmanager
|
|
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from psycopg_pool import AsyncConnectionPool, PoolTimeout
|
|
|
|
from app import config
|
|
from app.errors import unavailable
|
|
|
|
BROKEN = (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout)
|
|
|
|
|
|
async def discard(conn) -> None:
|
|
try:
|
|
await conn.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
class Guarded:
|
|
def __init__(self, conn, timeout: float):
|
|
self.conn = conn
|
|
self.timeout = timeout
|
|
|
|
async def execute(self, *args, **kwargs):
|
|
try:
|
|
return await asyncio.wait_for(self.conn.execute(*args, **kwargs), self.timeout)
|
|
except asyncio.TimeoutError:
|
|
await discard(self.conn)
|
|
raise unavailable("Хранилище не ответило за отведённое время") from None
|
|
|
|
def transaction(self):
|
|
return self.conn.transaction()
|
|
|
|
|
|
class Database:
|
|
def __init__(self) -> None:
|
|
options = "-c statement_timeout=%d -c lock_timeout=%d -c idle_in_transaction_session_timeout=%d" % (
|
|
config.DB_STATEMENT_TIMEOUT_MS,
|
|
config.DB_STATEMENT_TIMEOUT_MS,
|
|
config.DB_STATEMENT_TIMEOUT_MS * 2,
|
|
)
|
|
self.pool = AsyncConnectionPool(
|
|
conninfo=config.DATABASE_URL,
|
|
min_size=config.DB_POOL_MIN,
|
|
max_size=config.DB_POOL_MAX,
|
|
timeout=config.DB_POOL_TIMEOUT,
|
|
max_lifetime=600.0,
|
|
open=False,
|
|
kwargs={
|
|
"autocommit": True,
|
|
"row_factory": dict_row,
|
|
"connect_timeout": config.DB_CONNECT_TIMEOUT,
|
|
"options": options,
|
|
},
|
|
)
|
|
|
|
async def open(self) -> None:
|
|
await self.pool.open(wait=False)
|
|
|
|
async def close(self) -> None:
|
|
await self.pool.close()
|
|
|
|
@asynccontextmanager
|
|
async def connection(self):
|
|
try:
|
|
async with self.pool.connection(timeout=config.DB_POOL_TIMEOUT) as conn:
|
|
yield Guarded(conn, config.DB_OP_TIMEOUT)
|
|
except BROKEN:
|
|
raise unavailable("Хранилище недоступно") from None
|
|
|
|
@asynccontextmanager
|
|
async def transaction(self):
|
|
async with self.connection() as conn:
|
|
async with conn.transaction():
|
|
yield conn
|
|
|
|
async def in_transaction(self, action):
|
|
async def run():
|
|
async with self.transaction() as conn:
|
|
return await action(conn)
|
|
|
|
try:
|
|
return await asyncio.wait_for(run(), config.DB_OP_TIMEOUT)
|
|
except asyncio.TimeoutError:
|
|
raise unavailable("Хранилище не ответило за отведённое время") from None
|
|
|
|
async def ready(self) -> bool:
|
|
try:
|
|
async with self.pool.connection(timeout=config.DB_READY_TIMEOUT) as conn:
|
|
try:
|
|
await asyncio.wait_for(conn.execute("SELECT 1"), config.DB_READY_TIMEOUT)
|
|
except asyncio.TimeoutError:
|
|
await discard(conn)
|
|
return False
|
|
return True
|
|
except Exception:
|
|
return False
|