forked from mtusi2026/mtusi2026lab2
Carry over the lab 3 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy and k6 configuration, migrations, hooks, evidence and level 4
scripts and the CI job from the lab 3 solution commit 61c0c28, merge
the lab 3 Makefile targets into the lab 4 skeleton Makefile without
touching its targets, and append the lab 3 solution variables to the
skeleton .env.example. The package and the application follow the
contract version 1.4.0, and the image and the throwaway test containers
are tagged lab4 so they do not collide with a lab 3 stand on the same
host.
This is the starting point of the lab 4 cycle: lint, own tests and the
offline skeleton check pass before any lab 4 change.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b0f463ac5c
commit
bf8e4e3cd1
@@ -0,0 +1,118 @@
|
||||
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
|
||||
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
|
||||
Reference in New Issue
Block a user