Forward the lab 5 foundation while preserving lab 6 telemetry
Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files.
Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
This commit is contained in:
@@ -38,30 +38,23 @@ class CommandBus:
|
||||
|
||||
|
||||
class EventBus:
|
||||
__slots__ = ("_deferred", "_dropped", "_logger", "_projections", "_queue", "_worker")
|
||||
__slots__ = ("_deferred", "_dropped", "_logger", "_queue", "_worker")
|
||||
|
||||
def __init__(self, logger: Logger, *, max_queue: int = 10_000) -> None:
|
||||
self._logger = logger
|
||||
self._queue: asyncio.Queue[tuple[DomainEvent, contextvars.Context]] = asyncio.Queue(
|
||||
maxsize=max_queue
|
||||
)
|
||||
self._projections: dict[type[DomainEvent], list[Any]] = {}
|
||||
self._deferred: dict[type[DomainEvent], list[Any]] = {}
|
||||
self._worker: asyncio.Task[None] | None = None
|
||||
self._dropped = 0
|
||||
|
||||
def project[EventT: DomainEvent](
|
||||
self, event_type: type[EventT], handler: EventHandler[EventT]
|
||||
) -> None:
|
||||
self._projections.setdefault(event_type, []).append(handler)
|
||||
|
||||
def subscribe[EventT: DomainEvent](
|
||||
self, event_type: type[EventT], handler: EventHandler[EventT]
|
||||
) -> None:
|
||||
self._deferred.setdefault(event_type, []).append(handler)
|
||||
|
||||
async def emit(self, event: DomainEvent) -> bool:
|
||||
await self._run(self._projections.get(type(event), []), event, "projection")
|
||||
if not self._deferred.get(type(event)):
|
||||
return True
|
||||
try:
|
||||
@@ -100,11 +93,11 @@ class EventBus:
|
||||
event, context = await self._queue.get()
|
||||
handlers = self._deferred.get(type(event), [])
|
||||
try:
|
||||
await asyncio.create_task(self._run(handlers, event, "subscriber"), context=context)
|
||||
await asyncio.create_task(self._run(handlers, event), context=context)
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
async def _run(self, handlers: Sequence[Any], event: DomainEvent, kind: str) -> None:
|
||||
async def _run(self, handlers: Sequence[Any], event: DomainEvent) -> None:
|
||||
for handler in handlers:
|
||||
try:
|
||||
await handler(event)
|
||||
@@ -112,7 +105,6 @@ class EventBus:
|
||||
self._logger.error(
|
||||
"event.handler_failed",
|
||||
event_name=event.name,
|
||||
reason=kind,
|
||||
error=type(error).__name__,
|
||||
)
|
||||
|
||||
|
||||
@@ -26,6 +26,11 @@ class Logger(Protocol):
|
||||
def error(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Readiness(Protocol):
|
||||
async def check(self) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class UnitOfWork(Protocol):
|
||||
def transaction(self) -> AbstractAsyncContextManager[None]: ...
|
||||
|
||||
@@ -9,7 +9,7 @@ from messenger.shared.entrypoints.errors import Unauthenticated
|
||||
async def current_actor(request: Request) -> UUID:
|
||||
actor = getattr(request.state, "actor", None)
|
||||
if not isinstance(actor, UUID):
|
||||
raise Unauthenticated("заголовок идентификации обязателен и должен быть действительным")
|
||||
raise Unauthenticated("сессия не подтверждена")
|
||||
return actor
|
||||
|
||||
|
||||
|
||||
@@ -7,4 +7,4 @@ class TransportSettings(Settings):
|
||||
docs: bool = False
|
||||
max_body_bytes: int = Field(default=1_048_576, ge=4_096)
|
||||
request_timeout_seconds: float = Field(default=8.0, gt=0, le=300)
|
||||
shutdown_timeout_seconds: int = Field(default=5, ge=1, le=10)
|
||||
min_transfer_rate_bytes: int = Field(default=131_072, ge=1_024)
|
||||
|
||||
@@ -46,7 +46,7 @@ class Unauthenticated(Exception):
|
||||
|
||||
def classify(error: DomainError, codes: ErrorCodes) -> tuple[str, int]:
|
||||
for kind in type(error).__mro__:
|
||||
known = codes.get(kind) # type: ignore[arg-type]
|
||||
known = codes.get(kind)
|
||||
if known is not None:
|
||||
return known
|
||||
return "internal_error", status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
from threading import Event
|
||||
|
||||
from dishka.integrations.fastapi import FromDishka, inject
|
||||
from fastapi import APIRouter
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Readiness
|
||||
from messenger.shared.entrypoints.schemas import HealthOut
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
DRAINING = Event()
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
@@ -18,8 +14,6 @@ async def live() -> HealthOut:
|
||||
|
||||
@router.get("/health/ready")
|
||||
@inject
|
||||
async def ready(database: FromDishka[Database]) -> HealthOut:
|
||||
if DRAINING.is_set():
|
||||
raise Unavailable("Реплика выходит из ротации")
|
||||
await database.ping()
|
||||
async def ready(readiness: FromDishka[Readiness]) -> HealthOut:
|
||||
await readiness.check()
|
||||
return HealthOut()
|
||||
|
||||
@@ -3,11 +3,12 @@ from collections.abc import AsyncIterator
|
||||
from dishka import Provider, Scope, provide
|
||||
|
||||
from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger, Readiness
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
from messenger.shared.infrastructure.ids import Uuid7Generator
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
from messenger.shared.infrastructure.readiness import DatabaseReadiness
|
||||
|
||||
|
||||
class PlatformProvider(Provider):
|
||||
@@ -45,6 +46,10 @@ class PlatformProvider(Provider):
|
||||
yield database
|
||||
await database.close()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def readiness(self, database: Database) -> Readiness:
|
||||
return DatabaseReadiness(database)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def event_bus(self, logger: Logger, settings: PlatformSettings) -> EventBus:
|
||||
return EventBus(logger, max_queue=settings.event_queue_max)
|
||||
|
||||
@@ -5,6 +5,7 @@ from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from uuid import uuid4
|
||||
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
@@ -58,8 +59,44 @@ async def send_error(
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
|
||||
|
||||
class Pace:
|
||||
__slots__ = ("_deadline", "_moved", "_opened", "_rate", "_timeout")
|
||||
|
||||
def __init__(self, deadline: asyncio.Timeout, timeout: float, rate: float) -> None:
|
||||
self._deadline = deadline
|
||||
self._timeout = timeout
|
||||
self._rate = rate
|
||||
self._opened = asyncio.get_running_loop().time()
|
||||
self._moved = 0
|
||||
|
||||
def around(self, receive: Receive, send: Send) -> tuple[Receive, Send]:
|
||||
async def paced_receive() -> Message:
|
||||
return self._count(await receive())
|
||||
|
||||
async def paced_send(message: Message) -> None:
|
||||
await send(self._count(message))
|
||||
|
||||
return paced_receive, paced_send
|
||||
|
||||
def _count(self, message: Message) -> Message:
|
||||
if size := len(message.get("body", b"")):
|
||||
self._moved += size
|
||||
moved = min(asyncio.get_running_loop().time(), self._opened + self._moved / self._rate)
|
||||
self._deadline.reschedule(moved + self._timeout)
|
||||
return message
|
||||
|
||||
|
||||
class RequestPipeline:
|
||||
__slots__ = ("_app", "_guard", "_instance", "_limits", "_logger", "_max_bytes", "_timeout")
|
||||
__slots__ = (
|
||||
"_app",
|
||||
"_guard",
|
||||
"_instance",
|
||||
"_limits",
|
||||
"_logger",
|
||||
"_max_bytes",
|
||||
"_min_rate",
|
||||
"_timeout",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -70,12 +107,14 @@ class RequestPipeline:
|
||||
guard: Guard,
|
||||
instance: str,
|
||||
limits: BodyLimits = (),
|
||||
min_rate: float = 131_072,
|
||||
) -> None:
|
||||
self._app = app
|
||||
self._logger = logger
|
||||
self._max_bytes = max_bytes
|
||||
self._limits = limits
|
||||
self._timeout = timeout
|
||||
self._min_rate = min_rate
|
||||
self._guard = guard
|
||||
self._instance = instance.encode()
|
||||
|
||||
@@ -87,9 +126,7 @@ class RequestPipeline:
|
||||
incoming = header(scope, HEADER_BYTES)
|
||||
request_id = incoming[:MAX_REQUEST_ID] if incoming else uuid4().hex
|
||||
tag_request(request_id)
|
||||
state = scope.setdefault("state", {})
|
||||
state["request_id"] = request_id
|
||||
state["actor"] = None
|
||||
scope.setdefault("state", {}).update(request_id=request_id, actor=None)
|
||||
started = time.perf_counter()
|
||||
status_holder = [500]
|
||||
answered = [False]
|
||||
@@ -108,18 +145,23 @@ class RequestPipeline:
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
declared = header(scope, b"content-length")
|
||||
if declared.isdigit() and int(declared) > self._limit(scope["path"]):
|
||||
await send_error(wrapped_send, 413, "payload_too_large", request_id)
|
||||
self._log(scope, status_holder[0], request_id, started)
|
||||
return
|
||||
limit = self._limit(scope["path"])
|
||||
received = [0]
|
||||
|
||||
async def limited_receive() -> Message:
|
||||
message = await receive()
|
||||
received[0] += len(message.get("body", b""))
|
||||
if received[0] > limit:
|
||||
raise HTTPException(413)
|
||||
return message
|
||||
|
||||
rejection: Rejection | None = None
|
||||
try:
|
||||
async with asyncio.timeout(self._timeout):
|
||||
rejection = await self._guard(scope)
|
||||
async with asyncio.timeout(self._timeout) as deadline:
|
||||
rejection = await self._guard(scope) or self._oversized(scope, limit)
|
||||
if rejection is None:
|
||||
await self._app(scope, receive, wrapped_send)
|
||||
pace = Pace(deadline, self._timeout, self._min_rate)
|
||||
await self._app(scope, *pace.around(limited_receive, wrapped_send))
|
||||
except Unavailable as error:
|
||||
self._logger.warning(
|
||||
"dependency.unavailable",
|
||||
@@ -128,18 +170,21 @@ class RequestPipeline:
|
||||
request_id=request_id,
|
||||
)
|
||||
rejection = Rejection(503, "unavailable")
|
||||
except TimeoutError:
|
||||
except (TimeoutError, asyncio.CancelledError) as error:
|
||||
cancelled = isinstance(error, asyncio.CancelledError)
|
||||
self._logger.warning(
|
||||
"request.timeout",
|
||||
"request.cancelled" if cancelled else "request.timeout",
|
||||
method=scope["method"],
|
||||
route=self._route(scope),
|
||||
request_id=request_id,
|
||||
limit=self._timeout,
|
||||
limit=None if cancelled else self._timeout,
|
||||
duration_ms=round((time.perf_counter() - started) * 1000, 3),
|
||||
)
|
||||
if not answered[0]:
|
||||
await send_error(wrapped_send, 503, "unavailable", request_id)
|
||||
self._log(scope, status_holder[0], request_id, started)
|
||||
if cancelled:
|
||||
raise
|
||||
return
|
||||
except Exception:
|
||||
self._logger.error(
|
||||
@@ -162,6 +207,12 @@ class RequestPipeline:
|
||||
return limit
|
||||
return self._max_bytes
|
||||
|
||||
def _oversized(self, scope: Scope, limit: int) -> Rejection | None:
|
||||
declared = header(scope, b"content-length")
|
||||
if declared.isdigit() and int(declared) > limit:
|
||||
return Rejection(413, "payload_too_large")
|
||||
return None
|
||||
|
||||
def _route(self, scope: Scope) -> str:
|
||||
route = scope.get("route")
|
||||
return getattr(route, "path", scope["path"])
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
import sys
|
||||
from typing import Any
|
||||
from typing import Any, TextIO
|
||||
|
||||
import orjson
|
||||
import structlog
|
||||
@@ -62,7 +62,11 @@ def add_trace_context(_logger: WrappedLogger, _method: str, event_dict: EventDic
|
||||
return event_dict
|
||||
|
||||
|
||||
def configure(level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIELDS) -> None:
|
||||
def configure(
|
||||
level: str = "INFO",
|
||||
allowed_fields: frozenset[str] = PLATFORM_FIELDS,
|
||||
stream: TextIO | None = None,
|
||||
) -> None:
|
||||
shared = [
|
||||
structlog.contextvars.merge_contextvars,
|
||||
structlog.processors.add_log_level,
|
||||
@@ -75,7 +79,7 @@ def configure(level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIE
|
||||
wrapper_class=structlog.stdlib.BoundLogger,
|
||||
cache_logger_on_first_use=False,
|
||||
)
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler = logging.StreamHandler(stream or sys.stdout)
|
||||
handler.setFormatter(
|
||||
structlog.stdlib.ProcessorFormatter(
|
||||
foreign_pre_chain=shared,
|
||||
@@ -111,8 +115,9 @@ class StructlogLogger:
|
||||
name: str = "messenger",
|
||||
level: str = "INFO",
|
||||
allowed_fields: frozenset[str] = PLATFORM_FIELDS,
|
||||
stream: TextIO | None = None,
|
||||
) -> None:
|
||||
configure(level, allowed_fields)
|
||||
configure(level, allowed_fields, stream)
|
||||
self._logger = structlog.get_logger(name)
|
||||
|
||||
def info(self, event: str, /, **fields: Any) -> None:
|
||||
|
||||
@@ -1,32 +1,45 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, Protocol
|
||||
from typing import ClassVar, Protocol
|
||||
|
||||
import asyncpg
|
||||
from sqlalchemy import Text, make_url, select
|
||||
from sqlalchemy.exc import DBAPIError, IntegrityError, InterfaceError, OperationalError
|
||||
from sqlalchemy.exc import TimeoutError as PoolTimeout
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
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,
|
||||
)
|
||||
FAILURES = (OSError, InterfaceError, OperationalError, PoolTimeout, TimeoutError)
|
||||
|
||||
PING_TIMEOUT_SECONDS = 0.4
|
||||
|
||||
type Connection = asyncpg.Connection
|
||||
type DatabaseSession = AsyncSession
|
||||
|
||||
|
||||
class EventSource(Protocol):
|
||||
def collect_events(self) -> list[DomainEvent]: ...
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
type_annotation_map: ClassVar = {str: Text}
|
||||
|
||||
|
||||
def unavailable(error: BaseException) -> bool:
|
||||
if isinstance(error, IntegrityError):
|
||||
return False
|
||||
if isinstance(error, FAILURES):
|
||||
return True
|
||||
if isinstance(error, DBAPIError) and error.connection_invalidated:
|
||||
return True
|
||||
state = getattr(error.orig if isinstance(error, DBAPIError) else error, "sqlstate", None)
|
||||
return isinstance(state, str) and (state.startswith(("08", "53", "57")) or state == "55P03")
|
||||
|
||||
|
||||
class Database:
|
||||
__slots__ = ("_acquire_timeout", "_pool")
|
||||
__slots__ = ("_engine", "_sessions")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -37,63 +50,71 @@ class Database:
|
||||
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",
|
||||
self._engine = create_async_engine(
|
||||
make_url(dsn).set(drivername="postgresql+asyncpg"),
|
||||
pool_size=max_size,
|
||||
max_overflow=0,
|
||||
pool_timeout=acquire_timeout,
|
||||
pool_recycle=60,
|
||||
pool_pre_ping=True,
|
||||
hide_parameters=True,
|
||||
connect_args={
|
||||
"timeout": connect_timeout,
|
||||
"command_timeout": command_timeout,
|
||||
"server_settings": {
|
||||
"statement_timeout": str(int(command_timeout * 1000)),
|
||||
"lock_timeout": str(int(command_timeout * 1000)),
|
||||
"idle_in_transaction_session_timeout": "10000",
|
||||
},
|
||||
},
|
||||
)
|
||||
self._sessions = async_sessionmaker(self._engine, expire_on_commit=False)
|
||||
|
||||
async def open(self) -> None:
|
||||
await self._pool
|
||||
pass
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._pool.close()
|
||||
await self._engine.dispose()
|
||||
|
||||
@asynccontextmanager
|
||||
async def connection(self, wait: float | None = None) -> AsyncIterator[Connection]:
|
||||
async def session(self) -> AsyncIterator[DatabaseSession]:
|
||||
try:
|
||||
async with self._pool.acquire(timeout=wait or self._acquire_timeout) as connection:
|
||||
yield connection
|
||||
except FAILURES as error:
|
||||
async with self._sessions() as session:
|
||||
yield session
|
||||
except Exception as error:
|
||||
if not unavailable(error):
|
||||
raise
|
||||
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)
|
||||
try:
|
||||
async with asyncio.timeout(PING_TIMEOUT_SECONDS):
|
||||
async with self.session() as session:
|
||||
await session.execute(select(1))
|
||||
except TimeoutError as error:
|
||||
raise Unavailable("PostgreSQL недоступен") from error
|
||||
|
||||
|
||||
class PostgresUnitOfWork:
|
||||
__slots__ = ("_committed", "_connection", "_database", "_events", "_transaction", "seen")
|
||||
__slots__ = ("_committed", "_database", "_events", "_session", "seen")
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
self._database = database
|
||||
self._connection: Connection | None = None
|
||||
self._transaction: Any = None
|
||||
self._session: DatabaseSession | None = None
|
||||
self._committed = False
|
||||
self._events: list[DomainEvent] = []
|
||||
self.seen: list[EventSource] = []
|
||||
|
||||
@property
|
||||
def connection(self) -> Connection:
|
||||
if self._connection is None:
|
||||
def session(self) -> DatabaseSession:
|
||||
if self._session is None:
|
||||
raise RuntimeError("репозиторий используется вне транзакции")
|
||||
return self._connection
|
||||
return self._session
|
||||
|
||||
@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()
|
||||
async with self._database.session() as session:
|
||||
self._session = session
|
||||
self._committed = False
|
||||
mark = len(self._events)
|
||||
try:
|
||||
@@ -101,12 +122,11 @@ class PostgresUnitOfWork:
|
||||
finally:
|
||||
if not self._committed:
|
||||
del self._events[mark:]
|
||||
await self._transaction.rollback()
|
||||
self.seen.clear()
|
||||
self._connection = None
|
||||
self._session = None
|
||||
|
||||
async def commit(self) -> None:
|
||||
await self._transaction.commit()
|
||||
await self.session.commit()
|
||||
self._committed = True
|
||||
for source in self.seen:
|
||||
self._events.extend(source.collect_events())
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
from threading import Event
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
DRAINING = Event()
|
||||
|
||||
|
||||
class DatabaseReadiness:
|
||||
__slots__ = ("_database", "_draining")
|
||||
|
||||
def __init__(self, database: Database, draining: Event = DRAINING) -> None:
|
||||
self._database = database
|
||||
self._draining = draining
|
||||
|
||||
async def check(self) -> None:
|
||||
if self._draining.is_set():
|
||||
raise Unavailable("Реплика выходит из ротации")
|
||||
await self._database.ping()
|
||||
Reference in New Issue
Block a user