Carry over the lab 2 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack, migrations, secret generator, restart hook, evidence scripts and CI job from the lab 2 solution commit 8cddb09 unchanged, merge the lab 2 Makefile targets into the lab 3 skeleton Makefile without touching its targets, and append the lab 2 solution variables to the skeleton .env.example. The package version follows the contract version 1.3.0. This is the starting point of the lab 3 cycle: lint, own tests and the offline skeleton check pass before any lab 3 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
0ec2f9dae3
commit
416ce4f9db
@@ -0,0 +1,17 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
TICK = timedelta(microseconds=1)
|
||||
|
||||
|
||||
class MonotonicUtcClock:
|
||||
__slots__ = ("_last",)
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._last: datetime | None = None
|
||||
|
||||
def now(self) -> datetime:
|
||||
current = datetime.now(UTC)
|
||||
if self._last is not None and current <= self._last:
|
||||
current = self._last + TICK
|
||||
self._last = current
|
||||
return current
|
||||
@@ -0,0 +1,8 @@
|
||||
from uuid import UUID, uuid7
|
||||
|
||||
|
||||
class Uuid7Generator:
|
||||
__slots__ = ()
|
||||
|
||||
def new_id(self) -> UUID:
|
||||
return uuid7()
|
||||
@@ -0,0 +1,113 @@
|
||||
import logging
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
import orjson
|
||||
import structlog
|
||||
from structlog.typing import EventDict, Processor, WrappedLogger
|
||||
|
||||
PLATFORM_FIELDS = frozenset(
|
||||
{
|
||||
"method",
|
||||
"route",
|
||||
"status",
|
||||
"duration_ms",
|
||||
"request_id",
|
||||
"event_name",
|
||||
"error",
|
||||
"reason",
|
||||
"limit",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def render(obj: object, **_kwargs: object) -> str:
|
||||
return orjson.dumps(obj).decode()
|
||||
|
||||
|
||||
RESERVED = frozenset({"event", "level", "ts", "logger"})
|
||||
|
||||
FOREIGN_LOGGERS = (
|
||||
"uvicorn",
|
||||
"uvicorn.error",
|
||||
"gunicorn",
|
||||
"gunicorn.error",
|
||||
"asyncio",
|
||||
)
|
||||
|
||||
SILENCED_LOGGERS = ("uvicorn.access", "gunicorn.access")
|
||||
|
||||
|
||||
def field_filter(allowed: frozenset[str]) -> Processor:
|
||||
def drop_unlisted_fields(
|
||||
_logger: WrappedLogger, _method: str, event_dict: EventDict
|
||||
) -> EventDict:
|
||||
return {
|
||||
key: value
|
||||
for key, value in event_dict.items()
|
||||
if (key in RESERVED or key in allowed) and value is not None
|
||||
}
|
||||
|
||||
return drop_unlisted_fields
|
||||
|
||||
|
||||
def configure(level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIELDS) -> None:
|
||||
shared = [
|
||||
structlog.contextvars.merge_contextvars,
|
||||
structlog.processors.add_log_level,
|
||||
structlog.processors.TimeStamper(fmt="iso", utc=True, key="ts"),
|
||||
]
|
||||
structlog.configure(
|
||||
processors=[*shared, structlog.stdlib.ProcessorFormatter.wrap_for_formatter],
|
||||
logger_factory=structlog.stdlib.LoggerFactory(),
|
||||
wrapper_class=structlog.stdlib.BoundLogger,
|
||||
cache_logger_on_first_use=False,
|
||||
)
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(
|
||||
structlog.stdlib.ProcessorFormatter(
|
||||
foreign_pre_chain=shared,
|
||||
processors=[
|
||||
structlog.stdlib.ProcessorFormatter.remove_processors_meta,
|
||||
field_filter(allowed_fields),
|
||||
structlog.processors.JSONRenderer(serializer=render),
|
||||
],
|
||||
)
|
||||
)
|
||||
root = logging.getLogger()
|
||||
for existing in list(root.handlers):
|
||||
root.removeHandler(existing)
|
||||
root.addHandler(handler)
|
||||
root.setLevel(level.upper())
|
||||
for name in FOREIGN_LOGGERS:
|
||||
foreign = logging.getLogger(name)
|
||||
for existing in list(foreign.handlers):
|
||||
foreign.removeHandler(existing)
|
||||
foreign.propagate = True
|
||||
for name in SILENCED_LOGGERS:
|
||||
silenced = logging.getLogger(name)
|
||||
for existing in list(silenced.handlers):
|
||||
silenced.removeHandler(existing)
|
||||
silenced.propagate = False
|
||||
|
||||
|
||||
class StructlogLogger:
|
||||
__slots__ = ("_logger",)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str = "messenger",
|
||||
level: str = "INFO",
|
||||
allowed_fields: frozenset[str] = PLATFORM_FIELDS,
|
||||
) -> None:
|
||||
configure(level, allowed_fields)
|
||||
self._logger = structlog.get_logger(name)
|
||||
|
||||
def info(self, event: str, /, **fields: Any) -> None:
|
||||
self._logger.info(event, **fields)
|
||||
|
||||
def warning(self, event: str, /, **fields: Any) -> None:
|
||||
self._logger.warning(event, **fields)
|
||||
|
||||
def error(self, event: str, /, **fields: Any) -> None:
|
||||
self._logger.error(event, **fields)
|
||||
@@ -0,0 +1,115 @@
|
||||
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
|
||||
Reference in New Issue
Block a user