forked from mtusi2026/mtusi2026lab4
A command may now run several transactions: the upload compensation commits a removal after the ready commit failed, and a sweep commits one removal per abandoned intent and ends with a rolled back lookup. The unit of work cleared every collected event on any rollback, and the command bus published nothing when the handler raised, so the audit trail lost discards that had really been committed. A rollback now drops only the events recorded inside that transaction, and the bus publishes what was collected even when the handler fails. Events still come only from committed transactions. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
120 lines
3.7 KiB
Python
120 lines
3.7 KiB
Python
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,
|
|
asyncpg.exceptions.LockNotAvailableError,
|
|
)
|
|
|
|
PING_TIMEOUT_SECONDS = 0.4
|
|
|
|
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, wait: float | None = None) -> AsyncIterator[Connection]:
|
|
try:
|
|
async with self._pool.acquire(timeout=wait or 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(PING_TIMEOUT_SECONDS) as connection:
|
|
await connection.fetchval("SELECT 1", timeout=PING_TIMEOUT_SECONDS)
|
|
|
|
|
|
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
|
|
mark = len(self._events)
|
|
try:
|
|
yield
|
|
finally:
|
|
if not self._committed:
|
|
del self._events[mark:]
|
|
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
|