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
+6 -6
View File
@@ -1,5 +1,4 @@
import asyncio
import logging
import os
import sys
from typing import Any
@@ -10,12 +9,13 @@ from uvicorn.server import Server
from uvicorn_worker import UvicornWorker
from messenger.main import LOG_FIELDS
from messenger.shared.entrypoints.health import DRAINING
from messenger.shared.infrastructure.logging import configure
from messenger.shared.infrastructure.logging import StructlogLogger, configure
from messenger.shared.infrastructure.readiness import DRAINING
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
SHUTDOWN_SECONDS = int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "5"))
SHUTDOWN_SECONDS = int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "6"))
DRAIN_SECONDS = float(os.environ.get("DRAIN_SECONDS", "2"))
LOGGER = StructlogLogger(level=LOG_LEVEL, allowed_fields=LOG_FIELDS)
class StructlogGunicornLogger(GunicornBaseLogger):
@@ -31,7 +31,7 @@ class DrainingServer(Server):
await super().main_loop()
if not self.force_exit:
DRAINING.set()
logging.getLogger("uvicorn.error").info("Draining for %.1f s", DRAIN_SECONDS)
LOGGER.info("service.draining", limit=DRAIN_SECONDS)
await asyncio.sleep(DRAIN_SECONDS)
@@ -40,7 +40,7 @@ class MessengerWorker(UvicornWorker):
"access_log": False,
"server_header": False,
"date_header": False,
"timeout_graceful_shutdown": max(1, int(SHUTDOWN_SECONDS - DRAIN_SECONDS)),
"timeout_graceful_shutdown": max(1, int(SHUTDOWN_SECONDS - DRAIN_SECONDS) - 1),
}
async def _serve(self) -> None:
+13 -9
View File
@@ -4,7 +4,7 @@ from messenger.identity.application.commands import CloseSession, OpenSession, R
from messenger.identity.application.ports import (
IdentityUnitOfWork,
PasswordHasher,
SessionDirectory,
SessionRevocations,
)
from messenger.identity.domain.events import SessionClosed, SessionOpened
from messenger.identity.domain.models import Session, User
@@ -62,15 +62,19 @@ class OpenSessionHandler:
class CloseSessionHandler:
__slots__ = ("_sessions", "_uow")
__slots__ = ("_revocations", "_uow")
def __init__(self, uow: IdentityUnitOfWork, sessions: SessionDirectory) -> None:
def __init__(self, uow: IdentityUnitOfWork, revocations: SessionRevocations) -> None:
self._uow = uow
self._sessions = sessions
self._revocations = revocations
async def __call__(self, command: CloseSession) -> None:
await self._sessions.invalidate(command.session)
async with self._uow.transaction():
await self._uow.sessions.remove(command.session.token_hash)
self._uow.record(SessionClosed(user_id=command.session.user_id))
await self._uow.commit()
await self._revocations.revoke(command.session)
try:
async with self._uow.transaction():
await self._uow.sessions.remove(command.session.token_hash)
self._uow.record(SessionClosed(user_id=command.session.user_id))
await self._uow.commit()
except BaseException:
await self._revocations.restore(command.session)
raise
+6 -1
View File
@@ -38,7 +38,12 @@ class UserDirectory(Protocol):
class SessionDirectory(Protocol):
async def find(self, token_hash: bytes, now: datetime) -> Session | None: ...
async def invalidate(self, session: Session) -> None: ...
@runtime_checkable
class SessionRevocations(Protocol):
async def revoke(self, session: Session) -> None: ...
async def restore(self, session: Session) -> None: ...
@runtime_checkable
+8 -3
View File
@@ -17,6 +17,7 @@ from messenger.identity.application.ports import (
IdentityUnitOfWork,
PasswordHasher,
SessionDirectory,
SessionRevocations,
UserDirectory,
)
from messenger.identity.application.queries import Authenticate, GetCurrentUser, VerifyCredentials
@@ -27,7 +28,7 @@ from messenger.identity.infrastructure.postgres import (
PostgresSessionDirectory,
PostgresUserDirectory,
)
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.identity.infrastructure.valkey import CachedSessionDirectory, NoRevocations
from messenger.shared.application.commands import Command
from messenger.shared.application.messagebus import CommandHandler
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
@@ -76,6 +77,10 @@ class IdentityProvider(Provider):
finally:
await client.aclose()
@provide(scope=Scope.APP)
def revocations(self, sessions: SessionDirectory) -> SessionRevocations:
return sessions if isinstance(sessions, CachedSessionDirectory) else NoRevocations()
@provide(scope=Scope.APP)
def verify(self, users: UserDirectory, hasher: PasswordHasher) -> VerifyCredentials:
return VerifyCredentials(users, hasher)
@@ -100,13 +105,13 @@ class IdentityProvider(Provider):
clock: Clock,
ids: IdGenerator,
hasher: PasswordHasher,
sessions: SessionDirectory,
revocations: SessionRevocations,
settings: IdentitySettings,
) -> IdentityCommandBus:
ttl = timedelta(seconds=settings.session_ttl_seconds)
handlers: dict[type[Command], CommandHandler] = {
RegisterUser: RegisterUserHandler(uow, clock, ids, hasher),
OpenSession: OpenSessionHandler(uow, clock, ttl),
CloseSession: CloseSessionHandler(uow, sessions),
CloseSession: CloseSessionHandler(uow, revocations),
}
return IdentityCommandBus(handlers, uow, publisher)
@@ -119,6 +119,3 @@ class PostgresSessionDirectory:
async with self._database.connection() as connection:
row = await connection.fetchrow(ACTIVE_SESSION, token_hash, now)
return None if row is None else Session(**dict(row))
async def invalidate(self, session: Session) -> None:
return None
@@ -37,6 +37,14 @@ def decode(token_hash: bytes, value: str) -> Session:
)
class NoRevocations:
async def revoke(self, session: Session) -> None:
return None
async def restore(self, session: Session) -> None:
return None
class CachedSessionDirectory:
__slots__ = ("_client", "_cooldown", "_limit", "_logger", "_origin", "_resume_at")
@@ -70,7 +78,7 @@ class CachedSessionDirectory:
await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True))
return session
async def invalidate(self, session: Session) -> None:
async def revoke(self, session: Session) -> None:
if not self._closed():
raise Unavailable("кэш сессий недоступен")
try:
@@ -81,6 +89,9 @@ class CachedSessionDirectory:
self._trip(error)
raise Unavailable("кэш сессий недоступен") from error
async def restore(self, session: Session) -> None:
await self._quietly(self._client.delete(key_of(session.token_hash)))
async def _read(self, key: str) -> str | None:
if not self._closed():
return None
+1 -1
View File
@@ -41,7 +41,7 @@ from messenger.shared.entrypoints.ioc import PlatformProvider
from messenger.shared.entrypoints.pipeline import RequestPipeline
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
TRANSPORT_FIELDS = frozenset({"dropped_total", "queue", "instance"})
TRANSPORT_FIELDS = frozenset({"dropped_total"})
LOG_FIELDS = (
PLATFORM_FIELDS | TRANSPORT_FIELDS | IDENTITY_FIELDS | MESSAGING_FIELDS | ATTACHMENT_FIELDS
+36 -24
View File
@@ -1,9 +1,14 @@
from datetime import timedelta
from messenger.messaging.application.commands import CreateChat, PostMessage
from messenger.messaging.application.ports import MessagingUnitOfWork
from messenger.messaging.domain.errors import ChatNotFound
from messenger.messaging.domain.models import Chat, Message, Receipt
from messenger.messaging.application.ports import ChatDirectory, MessageLog, MessagingUnitOfWork
from messenger.messaging.domain.errors import (
ChatNotFound,
InvalidAttachmentList,
InvalidMessageText,
)
from messenger.messaging.domain.models import Chat, Message, attachment_list
from messenger.messaging.domain.values import MessageText
from messenger.shared.application.ports import Clock, IdGenerator
@@ -30,34 +35,41 @@ class CreateChatHandler:
class PostMessageHandler:
__slots__ = ("_clock", "_ids", "_ttl", "_uow")
__slots__ = ("_chats", "_clock", "_ids", "_log", "_ttl", "_uow")
def __init__(
self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator, ttl: timedelta
self,
uow: MessagingUnitOfWork,
log: MessageLog,
chats: ChatDirectory,
clock: Clock,
ids: IdGenerator,
*,
ttl: timedelta,
) -> None:
self._uow = uow
self._log = log
self._chats = chats
self._clock = clock
self._ids = ids
self._ttl = ttl
async def __call__(self, command: PostMessage) -> Message:
async with self._uow.transaction():
chat = await self._uow.chats.get(command.chat_id)
if chat is None:
raise ChatNotFound("чат не найден")
now = self._clock.now()
message = chat.post(
message_id=self._ids.new_id(),
sender_id=command.sender_id,
text=command.text,
now=now,
attachment_ids=command.attachment_ids,
)
known = await self._uow.chats.receipt(
chat.id, command.sender_id, command.key, now - self._ttl
)
if known is not None:
return known.replay(command.fingerprint)
await self._uow.chats.append(Receipt(command.key, command.fingerprint, message))
await self._uow.commit()
try:
text = MessageText(command.text)
attachments = attachment_list(text, command.attachment_ids)
except InvalidMessageText, InvalidAttachmentList:
if await self._chats.chat_for_member(command.chat_id, command.sender_id) is None:
raise ChatNotFound("чат не найден") from None
raise
now = self._clock.now()
draft = Message(
self._ids.new_id(), command.chat_id, command.sender_id, text, now, attachments
)
receipt = await self._log.post(draft, command.key, command.fingerprint, now - self._ttl)
if receipt is None:
raise ChatNotFound("чат не найден")
message = receipt.replay(command.fingerprint)
if message.id == draft.id:
self._uow.record(message.posted())
return message
+4 -5
View File
@@ -18,14 +18,13 @@ class CursorCodec(Protocol):
class ChatRepository(Protocol):
async def add(self, chat: Chat) -> None: ...
async def get(self, chat_id: UUID) -> Chat | None: ...
async def receipt(
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
@runtime_checkable
class MessageLog(Protocol):
async def post(
self, message: Message, key: str, fingerprint: bytes, since: datetime
) -> Receipt | None: ...
async def append(self, receipt: Receipt) -> None: ...
@runtime_checkable
class MessagingUnitOfWork(UnitOfWork, Protocol):
@@ -43,7 +43,7 @@ class ListChats:
async def __call__(self, user_id: UUID, *, limit: int, cursor: str | None) -> Page[Chat]:
scope = chats_scope(user_id)
after: HistoryKey | None = self._cursors.decode(scope, cursor) if cursor else None
after: HistoryKey | None = None if cursor is None else self._cursors.decode(scope, cursor)
items, has_more = await self._chats.chats_of(user_id, after=after, limit=limit)
next_cursor = self._cursors.encode(scope, items[-1].key) if has_more and items else None
return Page(items=items, next_cursor=next_cursor)
@@ -67,7 +67,7 @@ class ReadHistory:
if await self._chats.chat_for_member(chat_id, user_id) is None:
raise ChatNotFound("чат не найден")
scope = messages_scope(chat_id)
after: HistoryKey | None = self._cursors.decode(scope, cursor) if cursor else None
after: HistoryKey | None = None if cursor is None else self._cursors.decode(scope, cursor)
items, has_more = await self._chats.history(chat_id, after=after, limit=limit)
next_cursor = self._cursors.encode(scope, items[-1].key) if has_more and items else None
return Page(items=items, next_cursor=next_cursor)
+11 -57
View File
@@ -1,10 +1,9 @@
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from datetime import datetime
from uuid import UUID
from messenger.messaging.domain.errors import (
ChatNotFound,
IdempotencyConflict,
InvalidAttachmentList,
InvalidChatData,
@@ -20,8 +19,6 @@ from messenger.messaging.domain.values import (
)
from messenger.shared.domain.events import DomainEvent
TICK = timedelta(microseconds=1)
@dataclass(frozen=True, slots=True)
class Message:
@@ -36,6 +33,15 @@ class Message:
def key(self) -> HistoryKey:
return (self.created_at, self.id.int)
def posted(self) -> MessagePosted:
return MessagePosted(
message_id=self.id,
chat_id=self.chat_id,
sender_id=self.sender_id,
text_length=len(self.text.value),
created_at=self.created_at,
)
def attachment_list(text: MessageText, attachment_ids: Sequence[UUID]) -> tuple[UUID, ...]:
if len(attachment_ids) > MESSAGE_ATTACHMENTS_MAX:
@@ -62,15 +68,7 @@ class Receipt:
class Chat:
__slots__ = (
"_events",
"_members",
"created_at",
"id",
"last_message_at",
"member_ids",
"title",
)
__slots__ = ("_events", "created_at", "id", "member_ids", "title")
def __init__(
self,
@@ -79,14 +77,11 @@ class Chat:
title: ChatTitle,
member_ids: Sequence[UUID],
created_at: datetime,
last_message_at: datetime | None = None,
) -> None:
self.id = chat_id
self.title = title
self.member_ids: tuple[UUID, ...] = tuple(member_ids)
self.created_at = created_at
self.last_message_at = last_message_at
self._members: frozenset[UUID] = frozenset(member_ids)
self._events: list[DomainEvent] = []
@classmethod
@@ -131,47 +126,6 @@ class Chat:
def record(self, event: DomainEvent) -> None:
self._events.append(event)
def is_member(self, user_id: UUID) -> bool:
return user_id in self._members
def require_member(self, user_id: UUID) -> None:
if not self.is_member(user_id):
raise ChatNotFound("чат не найден")
def post(
self,
*,
message_id: UUID,
sender_id: UUID,
text: str,
now: datetime,
attachment_ids: Sequence[UUID] = (),
) -> Message:
self.require_member(sender_id)
body = MessageText(text)
attachments = attachment_list(body, attachment_ids)
last = self.last_message_at
created_at = now if last is None or now > last else last + TICK
message = Message(
id=message_id,
chat_id=self.id,
sender_id=sender_id,
text=body,
created_at=created_at,
attachment_ids=attachments,
)
self.last_message_at = created_at
self.record(
MessagePosted(
message_id=message.id,
chat_id=self.id,
sender_id=sender_id,
text_length=len(message.text.value),
created_at=created_at,
)
)
return message
def collect_events(self) -> list[DomainEvent]:
events, self._events = self._events, []
return events
+14 -2
View File
@@ -5,12 +5,18 @@ from dishka import Provider, Scope, provide
from messenger.messaging.application.bus import MessagingCommandBus
from messenger.messaging.application.commands import CreateChat, PostMessage
from messenger.messaging.application.handlers import CreateChatHandler, PostMessageHandler
from messenger.messaging.application.ports import ChatDirectory, CursorCodec, MessagingUnitOfWork
from messenger.messaging.application.ports import (
ChatDirectory,
CursorCodec,
MessageLog,
MessagingUnitOfWork,
)
from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory
from messenger.messaging.config import MessagingSettings
from messenger.messaging.infrastructure.cursor import SignedCursorCodec
from messenger.messaging.infrastructure.postgres import (
PostgresChatDirectory,
PostgresMessageLog,
PostgresMessagingUnitOfWork,
)
from messenger.shared.application.commands import Command
@@ -32,6 +38,10 @@ class MessagingProvider(Provider):
def directory(self, database: Database) -> ChatDirectory:
return PostgresChatDirectory(database)
@provide(scope=Scope.APP)
def log(self, database: Database) -> MessageLog:
return PostgresMessageLog(database)
@provide(scope=Scope.APP)
def cursors(self, settings: MessagingSettings) -> CursorCodec:
return SignedCursorCodec(settings.cursor_secret.get_secret_value().encode())
@@ -56,6 +66,8 @@ class MessagingProvider(Provider):
def command_bus(
self,
uow: MessagingUnitOfWork,
log: MessageLog,
directory: ChatDirectory,
publisher: EventPublisher,
clock: Clock,
ids: IdGenerator,
@@ -64,6 +76,6 @@ class MessagingProvider(Provider):
ttl = timedelta(seconds=settings.idempotency_ttl_seconds)
handlers: dict[type[Command], CommandHandler] = {
CreateChat: CreateChatHandler(uow, clock, ids),
PostMessage: PostMessageHandler(uow, clock, ids, ttl),
PostMessage: PostMessageHandler(uow, log, directory, clock, ids, ttl=ttl),
}
return MessagingCommandBus(handlers, uow, publisher)
@@ -37,7 +37,7 @@ class CreateMessageRequest(BaseModel):
class PageQuery(BaseModel):
limit: int = Field(default=50, ge=1, le=100)
cursor: str | None = None
cursor: str | None = Field(default=None, min_length=1)
class ChatOut(BaseModel):
@@ -1,4 +1,5 @@
from collections.abc import Sequence
from dataclasses import replace
from datetime import datetime
from uuid import UUID
@@ -8,6 +9,7 @@ from messenger.messaging.domain.errors import InvalidChatData, UnknownAttachment
from messenger.messaging.domain.keys import HistoryKey
from messenger.messaging.domain.models import Chat, Message, Receipt
from messenger.messaging.domain.values import ChatTitle, MessageText
from messenger.shared.application.errors import Unavailable
from messenger.shared.infrastructure.postgres import (
Connection,
Database,
@@ -21,12 +23,33 @@ INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
SELECT $1, member.user_id, member.position, $3
FROM unnest($2::uuid[]) WITH ORDINALITY AS member (user_id, position)
"""
LOCK_CHAT = """
SELECT c.id, c.title, c.created_at, c.last_message_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
FROM chats c
WHERE c.id = $1
FOR UPDATE
POST_MESSAGE = """
WITH chat AS (
SELECT c.id, GREATEST($5::timestamptz, c.last_message_at + interval '1 microsecond') AS stamp
FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $3
WHERE c.id = $2
FOR UPDATE OF c
), receipt AS (
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
SELECT id, $3, $6, $7, $1, stamp FROM chat
ON CONFLICT (chat_id, user_id, key) DO UPDATE
SET fingerprint = EXCLUDED.fingerprint,
message_id = EXCLUDED.message_id,
created_at = EXCLUDED.created_at
WHERE idempotency_keys.created_at <= $8
RETURNING created_at
), message AS (
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT $1, $2, $3, $4, created_at FROM receipt
RETURNING created_at
), links AS (
INSERT INTO message_attachments (message_id, position, chat_id, attachment_id)
SELECT $1, link.position - 1, $2, link.attachment_id
FROM message, unnest($9::uuid[]) WITH ORDINALITY AS link (attachment_id, position)
), touched AS (
UPDATE chats SET last_message_at = message.created_at FROM message WHERE chats.id = $2
)
SELECT EXISTS (SELECT FROM chat) AS member, (SELECT created_at FROM message) AS created_at
"""
ATTACHMENT_FKEY = "message_attachments_attachment_fkey"
RECEIPT = """
@@ -36,27 +59,6 @@ SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4
"""
APPEND_MESSAGE = """
WITH message AS (
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, chat_id, sender_id, created_at
), links AS (
INSERT INTO message_attachments (message_id, position, chat_id, attachment_id)
SELECT message.id, link.position - 1, message.chat_id, link.attachment_id
FROM message, unnest($8::uuid[]) WITH ORDINALITY AS link (attachment_id, position)
), receipt AS (
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
SELECT chat_id, sender_id, $6, $7, id, created_at FROM message
ON CONFLICT (chat_id, user_id, key) DO UPDATE
SET fingerprint = EXCLUDED.fingerprint,
message_id = EXCLUDED.message_id,
created_at = EXCLUDED.created_at
)
UPDATE chats SET last_message_at = message.created_at
FROM message
WHERE chats.id = message.chat_id
"""
CHAT_OF_MEMBER = """
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
@@ -105,7 +107,6 @@ def chat_of(row: Record) -> Chat:
title=ChatTitle(row["title"]),
member_ids=row["member_ids"],
created_at=row["created_at"],
last_message_at=row.get("last_message_at"),
)
@@ -141,38 +142,43 @@ class PostgresChatRepository:
raise InvalidChatData("поле member_ids содержит неизвестного пользователя") from error
self._seen.append(chat)
async def get(self, chat_id: UUID) -> Chat | None:
row = await self._connection.fetchrow(LOCK_CHAT, chat_id)
if row is None:
return None
chat = chat_of(row)
self._seen.append(chat)
return chat
async def receipt(
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
class PostgresMessageLog:
__slots__ = ("_database",)
def __init__(self, database: Database) -> None:
self._database = database
async def post(
self, message: Message, key: str, fingerprint: bytes, since: datetime
) -> Receipt | None:
row = await self._connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
return None if row is None else Receipt(key, row["fingerprint"], message_of(row))
async def append(self, receipt: Receipt) -> None:
message = receipt.message
try:
await self._connection.execute(
APPEND_MESSAGE,
message.id,
message.chat_id,
message.sender_id,
message.text.value,
message.created_at,
receipt.key,
receipt.fingerprint,
list(message.attachment_ids),
)
except ForeignKeyViolationError as error:
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
raise
raise UnknownAttachment("вложение не найдено в этом чате") from error
chat_id, sender_id = message.chat_id, message.sender_id
async with self._database.connection() as connection:
try:
row = await connection.fetchrow(
POST_MESSAGE,
message.id,
chat_id,
sender_id,
message.text.value,
message.created_at,
key,
fingerprint,
since,
list(message.attachment_ids),
)
except ForeignKeyViolationError as error:
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
raise
raise UnknownAttachment("вложение не найдено в этом чате") from error
if row is None or not row["member"]:
return None
if row["created_at"] is not None:
return Receipt(key, fingerprint, replace(message, created_at=row["created_at"]))
known = await connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
if known is None:
raise Unavailable("ключ идемпотентности занят незавершённой записью")
return Receipt(key, known["fingerprint"], message_of(known))
class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
+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()