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
+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):