Carry over the lab 3 fixes made after 61c0c28

Bring the system changes of lab 3 from 61c0c28..72a1e57 onto the lab 4
code, resolving each conflict by meaning and keeping everything lab 4
added:

- a message is posted with one SQL statement under the chat row lock,
  and the attachment links go into the same statement; a foreign key
  violation on the attachment link still answers 404 and leaves nothing
  behind. Text and the attachment list are checked before the write, an
  outsider gets 404 for both, as before the carry over;
- the request pipeline counts the body bytes actually received against
  the limit of the route, so a chunked body over 1 MiB gets 413 and the
  upload route keeps its MAX_UPLOAD_BYTES limit;
- a request cancelled at shutdown gets 503 unavailable in the contract
  format, the worker waits a second less than the rest of the shutdown
  budget, SHUTDOWN_TIMEOUT_SECONDS becomes 6 s and the stop hooks 7 s;
- readiness sits behind a Readiness port with the draining flag in
  shared infrastructure, and the drain window is logged through Logger;
- logout revokes through SessionRevocations and withdraws the mark when
  PostgreSQL rejects the delete; an empty cursor is 400;
- EventBus.project is gone, the sweep test subscribes and waits on a
  queue; domain tests check attachment_list instead of Chat.post;
- make up waits for every replica in the balancer, BASE_URL follows the
  lb port, the image is tagged by the compose project, retry-check and
  faults-evidence are added, detection runs three times, failover-each
  and rolling-update record the stand usage, CI checks numeric uids.
  down also takes the tools and reconcile profiles of lab 4.

Track 1 tooling of lab 3 (scaling.py, its samplers, tools/ and the CPU
pinning of api, lb, valkey and k6) stays out; stand-usage.sh queries the
database size itself instead of the track 1 sampler.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-30 06:25:23 +03:00
co-authored by Claude Opus 5.5
parent 7ac1a4a11b
commit e927afdb09
56 changed files with 932 additions and 397 deletions
+3 -11
View File
@@ -37,28 +37,21 @@ 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[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:
@@ -96,11 +89,11 @@ class EventBus:
while True:
event = await self._queue.get()
try:
await self._run(self._deferred.get(type(event), []), event, "subscriber")
await self._run(self._deferred.get(type(event), []), event)
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)
@@ -108,7 +101,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]: ...
+1 -1
View File
@@ -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,3 @@ 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)
+1 -1
View File
@@ -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
+3 -9
View File
@@ -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()
+6 -1
View File
@@ -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)
+24 -10
View File
@@ -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
@@ -106,18 +107,22 @@ 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)
rejection = self._oversized(scope, limit) or await self._guard(scope)
if rejection is None:
await self._app(scope, receive, wrapped_send)
await self._app(scope, limited_receive, wrapped_send)
except Unavailable as error:
self._logger.warning(
"dependency.unavailable",
@@ -126,18 +131,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(
@@ -160,6 +168,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"])
@@ -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()