from collections.abc import AsyncIterator from contextlib import asynccontextmanager from typing import Any, Protocol import asyncpg from messenger.shared.application.errors import Unavailable from messenger.shared.domain.events import DomainEvent FAILURES = ( OSError, asyncpg.InterfaceError, asyncpg.PostgresConnectionError, asyncpg.exceptions.OperatorInterventionError, asyncpg.exceptions.InsufficientResourcesError, ) type Connection = asyncpg.Connection class EventSource(Protocol): def collect_events(self) -> list[DomainEvent]: ... class Database: __slots__ = ("_acquire_timeout", "_pool") def __init__( self, dsn: str, *, max_size: int, connect_timeout: float, acquire_timeout: float, command_timeout: float, ) -> None: self._acquire_timeout = acquire_timeout self._pool = asyncpg.create_pool( dsn, min_size=0, max_size=max_size, timeout=connect_timeout, command_timeout=command_timeout, max_inactive_connection_lifetime=60, server_settings={ "statement_timeout": str(int(command_timeout * 1000)), "lock_timeout": str(int(command_timeout * 1000)), "idle_in_transaction_session_timeout": "10000", }, ) async def open(self) -> None: await self._pool async def close(self) -> None: await self._pool.close() @asynccontextmanager async def connection(self) -> AsyncIterator[Connection]: try: async with self._pool.acquire(timeout=self._acquire_timeout) as connection: yield connection except FAILURES as error: raise Unavailable("PostgreSQL недоступен") from error async def ping(self) -> None: async with self.connection() as connection: await connection.fetchval("SELECT 1", timeout=1) class PostgresUnitOfWork: __slots__ = ("_committed", "_connection", "_database", "_events", "_transaction", "seen") def __init__(self, database: Database) -> None: self._database = database self._connection: Connection | None = None self._transaction: Any = None self._committed = False self._events: list[DomainEvent] = [] self.seen: list[EventSource] = [] @property def connection(self) -> Connection: if self._connection is None: raise RuntimeError("репозиторий используется вне транзакции") return self._connection @asynccontextmanager async def transaction(self) -> AsyncIterator[None]: async with self._database.connection() as connection: self._connection = connection self._transaction = connection.transaction() await self._transaction.start() self._committed = False try: yield finally: if not self._committed: self._events.clear() await self._transaction.rollback() self.seen.clear() self._connection = None async def commit(self) -> None: await self._transaction.commit() self._committed = True for source in self.seen: self._events.extend(source.collect_events()) def record(self, event: DomainEvent) -> None: self._events.append(event) def collect_new_events(self) -> list[DomainEvent]: events, self._events = self._events, [] return events