forked from mtusi2026/mtusi2026lab4
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,2 @@
|
||||
class Command:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
class Unavailable(Exception):
|
||||
pass
|
||||
@@ -0,0 +1,123 @@
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.ports import EventPublisher, Logger, UnitOfWork
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
type CommandHandler = Callable[[Any], Awaitable[Any]]
|
||||
type EventHandler[EventT: DomainEvent] = Callable[[EventT], Awaitable[None]]
|
||||
|
||||
|
||||
class CommandBus:
|
||||
__slots__ = ("_handlers", "_publisher", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
handlers: Mapping[type[Command], CommandHandler],
|
||||
uow: UnitOfWork,
|
||||
publisher: EventPublisher,
|
||||
) -> None:
|
||||
self._handlers = handlers
|
||||
self._uow = uow
|
||||
self._publisher = publisher
|
||||
|
||||
async def execute(self, command: Command) -> Any:
|
||||
handler = self._handlers.get(type(command))
|
||||
if handler is None:
|
||||
raise LookupError(f"нет обработчика для команды {type(command).__name__}")
|
||||
result = await handler(command)
|
||||
events = self._uow.collect_new_events()
|
||||
if events:
|
||||
await self._publisher.publish(events)
|
||||
return result
|
||||
|
||||
|
||||
class EventBus:
|
||||
__slots__ = ("_deferred", "_dropped", "_logger", "_projections", "_queue", "_worker")
|
||||
|
||||
def __init__(self, logger: Logger, *, max_queue: int = 10_000) -> None:
|
||||
self._logger = logger
|
||||
self._queue: asyncio.Queue[DomainEvent] = 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:
|
||||
self._queue.put_nowait(event)
|
||||
except asyncio.QueueFull:
|
||||
self._dropped += 1
|
||||
self._logger.warning(
|
||||
"event.dropped", event_name=event.name, dropped_total=self._dropped
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
@property
|
||||
def dropped(self) -> int:
|
||||
return self._dropped
|
||||
|
||||
@property
|
||||
def pending(self) -> int:
|
||||
return self._queue.qsize()
|
||||
|
||||
def start(self) -> None:
|
||||
if self._worker is None:
|
||||
self._worker = asyncio.create_task(self._drain())
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._worker is None:
|
||||
return
|
||||
await self._queue.join()
|
||||
self._worker.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._worker
|
||||
self._worker = None
|
||||
|
||||
async def _drain(self) -> None:
|
||||
while True:
|
||||
event = await self._queue.get()
|
||||
try:
|
||||
await self._run(self._deferred.get(type(event), []), event, "subscriber")
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
async def _run(self, handlers: Sequence[Any], event: DomainEvent, kind: str) -> None:
|
||||
for handler in handlers:
|
||||
try:
|
||||
await handler(event)
|
||||
except Exception as error:
|
||||
self._logger.error(
|
||||
"event.handler_failed",
|
||||
event_name=event.name,
|
||||
reason=kind,
|
||||
error=type(error).__name__,
|
||||
)
|
||||
|
||||
|
||||
class InMemoryEventPublisher:
|
||||
__slots__ = ("_bus",)
|
||||
|
||||
def __init__(self, bus: EventBus) -> None:
|
||||
self._bus = bus
|
||||
|
||||
async def publish(self, events: Sequence[DomainEvent]) -> None:
|
||||
for event in events:
|
||||
await self._bus.emit(event)
|
||||
@@ -0,0 +1,42 @@
|
||||
from collections.abc import Sequence
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from datetime import datetime
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Clock(Protocol):
|
||||
def now(self) -> datetime: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class IdGenerator(Protocol):
|
||||
def new_id(self) -> UUID: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Logger(Protocol):
|
||||
def info(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
def warning(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
def error(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class UnitOfWork(Protocol):
|
||||
def transaction(self) -> AbstractAsyncContextManager[None]: ...
|
||||
|
||||
async def commit(self) -> None: ...
|
||||
|
||||
def record(self, event: DomainEvent) -> None: ...
|
||||
|
||||
def collect_new_events(self) -> list[DomainEvent]: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class EventPublisher(Protocol):
|
||||
async def publish(self, events: Sequence[DomainEvent]) -> None: ...
|
||||
@@ -0,0 +1,49 @@
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import Field, SecretStr
|
||||
from pydantic.fields import FieldInfo
|
||||
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
|
||||
|
||||
CONFIG = SettingsConfigDict(extra="ignore", frozen=True)
|
||||
|
||||
|
||||
class FileVariables(PydanticBaseSettingsSource):
|
||||
def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
|
||||
path = os.environ.get(f"{field_name.upper()}_FILE")
|
||||
return (Path(path).read_text().strip() if path else None), field_name, False
|
||||
|
||||
def __call__(self) -> dict[str, Any]:
|
||||
found = {
|
||||
name: self.get_field_value(field, name)[0]
|
||||
for name, field in self.settings_cls.model_fields.items()
|
||||
}
|
||||
return {name: value for name, value in found.items() if value is not None}
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = CONFIG
|
||||
|
||||
@classmethod
|
||||
def settings_customise_sources(
|
||||
cls,
|
||||
settings_cls: type[BaseSettings],
|
||||
init_settings: PydanticBaseSettingsSource,
|
||||
env_settings: PydanticBaseSettingsSource,
|
||||
dotenv_settings: PydanticBaseSettingsSource,
|
||||
file_secret_settings: PydanticBaseSettingsSource,
|
||||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||||
return init_settings, env_settings, FileVariables(settings_cls)
|
||||
|
||||
|
||||
class PlatformSettings(Settings):
|
||||
log_level: str = "INFO"
|
||||
instance_id: str = Field(default_factory=socket.gethostname, min_length=1)
|
||||
event_queue_max: int = Field(default=10_000, ge=16)
|
||||
database_url: SecretStr
|
||||
db_pool_max_size: int = Field(default=8, ge=1, le=50)
|
||||
db_connect_timeout_seconds: float = Field(default=1.0, gt=0, le=30)
|
||||
db_acquire_timeout_seconds: float = Field(default=1.0, gt=0, le=30)
|
||||
db_command_timeout_seconds: float = Field(default=2.0, gt=0, le=60)
|
||||
@@ -0,0 +1,4 @@
|
||||
class DomainError(Exception):
|
||||
def __init__(self, detail: str) -> None:
|
||||
super().__init__(detail)
|
||||
self.detail = detail
|
||||
@@ -0,0 +1,6 @@
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DomainEvent:
|
||||
name: str = field(init=False, default="domain.event")
|
||||
@@ -0,0 +1,16 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends, Request
|
||||
|
||||
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("заголовок идентификации обязателен и должен быть действительным")
|
||||
return actor
|
||||
|
||||
|
||||
type Actor = Annotated[UUID, Depends(current_actor)]
|
||||
@@ -0,0 +1,10 @@
|
||||
from pydantic import Field
|
||||
|
||||
from messenger.shared.config import Settings
|
||||
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,136 @@
|
||||
from collections.abc import Callable, Mapping
|
||||
|
||||
from fastapi import FastAPI, Request, Response, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Logger
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
from messenger.shared.entrypoints.schemas import ErrorEnvelope
|
||||
|
||||
REQUEST_ID_HEADER = "X-Request-Id"
|
||||
INSTANCE_ID_HEADER = "X-Instance-Id"
|
||||
|
||||
type ErrorCodes = Mapping[type[DomainError], tuple[str, int]]
|
||||
type Challenge = Callable[[str], str]
|
||||
|
||||
MESSAGES = {
|
||||
"invalid_request": "Запрос не соответствует контракту",
|
||||
"unauthorized": "Аутентификация не предоставлена или недействительна",
|
||||
"not_found": "Объект не найден",
|
||||
"conflict": "Конфликт состояния",
|
||||
"payload_too_large": "Тело запроса больше допустимого",
|
||||
"unsupported_media_type": "Неподдерживаемый тип содержимого",
|
||||
"rate_limited": "Слишком много запросов",
|
||||
"unavailable": "Сервис временно недоступен",
|
||||
"internal_error": "Внутренняя ошибка",
|
||||
}
|
||||
|
||||
STATUS_CODES = {
|
||||
status.HTTP_400_BAD_REQUEST: "invalid_request",
|
||||
status.HTTP_401_UNAUTHORIZED: "unauthorized",
|
||||
status.HTTP_404_NOT_FOUND: "not_found",
|
||||
status.HTTP_409_CONFLICT: "conflict",
|
||||
status.HTTP_413_CONTENT_TOO_LARGE: "payload_too_large",
|
||||
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE: "unsupported_media_type",
|
||||
status.HTTP_422_UNPROCESSABLE_CONTENT: "invalid_request",
|
||||
status.HTTP_429_TOO_MANY_REQUESTS: "rate_limited",
|
||||
status.HTTP_503_SERVICE_UNAVAILABLE: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
class Unauthenticated(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def classify(error: DomainError, codes: ErrorCodes) -> tuple[str, int]:
|
||||
for kind in type(error).__mro__:
|
||||
known = codes.get(kind) # type: ignore[arg-type]
|
||||
if known is not None:
|
||||
return known
|
||||
return "internal_error", status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
|
||||
def route_of(request: Request) -> str:
|
||||
route = request.scope.get("route")
|
||||
return getattr(route, "path", request.url.path)
|
||||
|
||||
|
||||
def install(
|
||||
app: FastAPI, logger: Logger, codes: ErrorCodes, challenge: Challenge, instance: str
|
||||
) -> None:
|
||||
def error_response(request: Request, code: str, detail: str, http_status: int) -> Response:
|
||||
request_id = getattr(request.state, "request_id", "") or "unknown"
|
||||
headers = {REQUEST_ID_HEADER: request_id, INSTANCE_ID_HEADER: instance}
|
||||
if http_status == status.HTTP_401_UNAUTHORIZED:
|
||||
headers["WWW-Authenticate"] = challenge(request.url.path)
|
||||
return Response(
|
||||
status_code=http_status,
|
||||
content=ErrorEnvelope.of(code, detail, request_id).model_dump_json(),
|
||||
media_type="application/json",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
@app.exception_handler(DomainError)
|
||||
async def _domain(request: Request, exc: DomainError) -> Response:
|
||||
code, http_status = classify(exc, codes)
|
||||
return error_response(request, code, exc.detail, http_status)
|
||||
|
||||
@app.exception_handler(Unavailable)
|
||||
async def _unavailable(request: Request, exc: Unavailable) -> Response:
|
||||
logger.warning(
|
||||
"dependency.unavailable",
|
||||
route=route_of(request),
|
||||
error=type(exc.__cause__ or exc).__name__,
|
||||
request_id=getattr(request.state, "request_id", None),
|
||||
)
|
||||
return error_response(
|
||||
request,
|
||||
"unavailable",
|
||||
MESSAGES["unavailable"],
|
||||
status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
)
|
||||
|
||||
@app.exception_handler(Unauthenticated)
|
||||
async def _unauthenticated(request: Request, _exc: Unauthenticated) -> Response:
|
||||
return error_response(
|
||||
request,
|
||||
"unauthorized",
|
||||
MESSAGES["unauthorized"],
|
||||
status.HTTP_401_UNAUTHORIZED,
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def _validation(request: Request, _exc: RequestValidationError) -> Response:
|
||||
return error_response(
|
||||
request,
|
||||
"invalid_request",
|
||||
MESSAGES["invalid_request"],
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def _http(request: Request, exc: HTTPException) -> Response:
|
||||
http_status = exc.status_code
|
||||
if http_status == status.HTTP_405_METHOD_NOT_ALLOWED:
|
||||
http_status = status.HTTP_404_NOT_FOUND
|
||||
code = STATUS_CODES.get(http_status, "internal_error")
|
||||
return error_response(
|
||||
request, code, MESSAGES.get(code, MESSAGES["internal_error"]), http_status
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def _unexpected(request: Request, exc: Exception) -> Response:
|
||||
logger.error(
|
||||
"request.failed",
|
||||
route=route_of(request),
|
||||
error=type(exc).__name__,
|
||||
request_id=getattr(request.state, "request_id", None),
|
||||
)
|
||||
return error_response(
|
||||
request,
|
||||
"internal_error",
|
||||
MESSAGES["internal_error"],
|
||||
status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
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.entrypoints.schemas import HealthOut
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
DRAINING = Event()
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
async def live() -> HealthOut:
|
||||
return HealthOut()
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
@inject
|
||||
async def ready(database: FromDishka[Database]) -> HealthOut:
|
||||
if DRAINING.is_set():
|
||||
raise Unavailable("Реплика выходит из ротации")
|
||||
await database.ping()
|
||||
return HealthOut()
|
||||
@@ -0,0 +1,54 @@
|
||||
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.config import PlatformSettings
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
from messenger.shared.infrastructure.ids import Uuid7Generator
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
class PlatformProvider(Provider):
|
||||
def __init__(self, settings: PlatformSettings, logger: Logger) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
self._logger = logger
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> PlatformSettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def logger(self) -> Logger:
|
||||
return self._logger
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def clock(self) -> Clock:
|
||||
return MonotonicUtcClock()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def ids(self) -> IdGenerator:
|
||||
return Uuid7Generator()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
async def database(self, settings: PlatformSettings) -> AsyncIterator[Database]:
|
||||
database = Database(
|
||||
settings.database_url.get_secret_value(),
|
||||
max_size=settings.db_pool_max_size,
|
||||
connect_timeout=settings.db_connect_timeout_seconds,
|
||||
acquire_timeout=settings.db_acquire_timeout_seconds,
|
||||
command_timeout=settings.db_command_timeout_seconds,
|
||||
)
|
||||
await database.open()
|
||||
yield database
|
||||
await database.close()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def event_bus(self, logger: Logger, settings: PlatformSettings) -> EventBus:
|
||||
return EventBus(logger, max_queue=settings.event_queue_max)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def publisher(self, bus: EventBus) -> EventPublisher:
|
||||
return InMemoryEventPublisher(bus)
|
||||
@@ -0,0 +1,165 @@
|
||||
import asyncio
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from uuid import uuid4
|
||||
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Logger
|
||||
from messenger.shared.entrypoints.errors import INSTANCE_ID_HEADER, MESSAGES, REQUEST_ID_HEADER
|
||||
from messenger.shared.entrypoints.schemas import ErrorEnvelope
|
||||
|
||||
type Headers = tuple[tuple[str, str], ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Rejection:
|
||||
status: int
|
||||
code: str
|
||||
headers: Headers = ()
|
||||
|
||||
|
||||
type Guard = Callable[[Scope], Awaitable[Rejection | None]]
|
||||
|
||||
HEADER_BYTES = REQUEST_ID_HEADER.lower().encode()
|
||||
INSTANCE_BYTES = INSTANCE_ID_HEADER.lower().encode()
|
||||
STAMPED = frozenset({HEADER_BYTES, INSTANCE_BYTES})
|
||||
MAX_REQUEST_ID = 200
|
||||
|
||||
|
||||
def header(scope: Scope, name: bytes) -> str:
|
||||
for key, value in scope["headers"]:
|
||||
if key == name:
|
||||
return value.decode("latin-1").strip()
|
||||
return ""
|
||||
|
||||
|
||||
async def send_error(
|
||||
send: Send, status: int, code: str, request_id: str, headers: Headers = ()
|
||||
) -> None:
|
||||
body = ErrorEnvelope.of(code, MESSAGES[code], request_id).model_dump_json().encode()
|
||||
await send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": status,
|
||||
"headers": [
|
||||
(b"content-type", b"application/json"),
|
||||
(b"content-length", str(len(body)).encode()),
|
||||
(HEADER_BYTES, request_id.encode("latin-1", "replace")),
|
||||
*((name.encode(), value.encode("latin-1")) for name, value in headers),
|
||||
],
|
||||
}
|
||||
)
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
|
||||
|
||||
class RequestPipeline:
|
||||
__slots__ = ("_app", "_guard", "_instance", "_logger", "_max_bytes", "_timeout")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
app: ASGIApp,
|
||||
logger: Logger,
|
||||
max_bytes: int,
|
||||
timeout: float,
|
||||
guard: Guard,
|
||||
instance: str,
|
||||
) -> None:
|
||||
self._app = app
|
||||
self._logger = logger
|
||||
self._max_bytes = max_bytes
|
||||
self._timeout = timeout
|
||||
self._guard = guard
|
||||
self._instance = instance.encode()
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
await self._app(scope, receive, send)
|
||||
return
|
||||
|
||||
incoming = header(scope, HEADER_BYTES)
|
||||
request_id = incoming[:MAX_REQUEST_ID] if incoming else uuid4().hex
|
||||
state = scope.setdefault("state", {})
|
||||
state["request_id"] = request_id
|
||||
state["actor"] = None
|
||||
started = time.perf_counter()
|
||||
status_holder = [500]
|
||||
answered = [False]
|
||||
|
||||
async def wrapped_send(message: Message) -> None:
|
||||
if message["type"] == "http.response.start":
|
||||
status_holder[0] = message["status"]
|
||||
answered[0] = True
|
||||
headers = [
|
||||
(key, value)
|
||||
for key, value in message.get("headers", [])
|
||||
if key.lower() not in STAMPED
|
||||
]
|
||||
headers.append((HEADER_BYTES, request_id.encode("latin-1", "replace")))
|
||||
headers.append((INSTANCE_BYTES, self._instance))
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
declared = header(scope, b"content-length")
|
||||
if declared.isdigit() and int(declared) > self._max_bytes:
|
||||
await send_error(wrapped_send, 413, "payload_too_large", request_id)
|
||||
self._log(scope, status_holder[0], request_id, started)
|
||||
return
|
||||
|
||||
rejection: Rejection | None = None
|
||||
try:
|
||||
async with asyncio.timeout(self._timeout):
|
||||
rejection = await self._guard(scope)
|
||||
if rejection is None:
|
||||
await self._app(scope, receive, wrapped_send)
|
||||
except Unavailable as error:
|
||||
self._logger.warning(
|
||||
"dependency.unavailable",
|
||||
route=self._route(scope),
|
||||
error=type(error.__cause__ or error).__name__,
|
||||
request_id=request_id,
|
||||
)
|
||||
rejection = Rejection(503, "unavailable")
|
||||
except TimeoutError:
|
||||
self._logger.warning(
|
||||
"request.timeout",
|
||||
method=scope["method"],
|
||||
route=self._route(scope),
|
||||
request_id=request_id,
|
||||
limit=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)
|
||||
return
|
||||
except Exception:
|
||||
self._logger.error(
|
||||
"request.unhandled",
|
||||
method=scope["method"],
|
||||
route=self._route(scope),
|
||||
request_id=request_id,
|
||||
duration_ms=round((time.perf_counter() - started) * 1000, 3),
|
||||
)
|
||||
raise
|
||||
if rejection is not None and not answered[0]:
|
||||
await send_error(
|
||||
wrapped_send, rejection.status, rejection.code, request_id, rejection.headers
|
||||
)
|
||||
self._log(scope, status_holder[0], request_id, started)
|
||||
|
||||
def _route(self, scope: Scope) -> str:
|
||||
route = scope.get("route")
|
||||
return getattr(route, "path", scope["path"])
|
||||
|
||||
def _log(self, scope: Scope, status: int, request_id: str, started: float) -> None:
|
||||
self._logger.info(
|
||||
"request.handled",
|
||||
method=scope["method"],
|
||||
route=self._route(scope),
|
||||
status=status,
|
||||
request_id=request_id,
|
||||
duration_ms=round((time.perf_counter() - started) * 1000, 3),
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ErrorDetail(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorEnvelope(BaseModel):
|
||||
error: ErrorDetail
|
||||
|
||||
@classmethod
|
||||
def of(cls, code: str, message: str, request_id: str) -> ErrorEnvelope:
|
||||
return cls(error=ErrorDetail(code=code, message=message, request_id=request_id))
|
||||
|
||||
|
||||
class HealthOut(BaseModel):
|
||||
status: Literal["ok"] = "ok"
|
||||
@@ -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,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