Carry over the lab 4 solution

Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6 and RustFS configuration, migrations, hooks, evidence and
scenario scripts and the CI job from the lab 4 solution commit d2744bc,
merge the lab 4 Makefile targets into the lab 5 skeleton Makefile
without touching its targets, and append the lab 4 solution variables
to the skeleton .env.example. The package and the application follow
the contract version 1.5.0, and the image and the throwaway test
containers are tagged lab5 so they do not collide with a lab 4 stand on
the same host.

This is the starting point of the lab 5 cycle: lint, own tests and the
offline skeleton check pass before any lab 5 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-29 00:34:03 +03:00
co-authored by Claude Opus 5.5
parent 1210dd899c
commit 540fcb35ba
171 changed files with 12909 additions and 1 deletions
@@ -0,0 +1,20 @@
from messenger.messaging.domain.errors import (
ChatNotFound,
IdempotencyConflict,
InvalidAttachmentList,
InvalidChatData,
InvalidMessageText,
InvalidPageRequest,
UnknownAttachment,
)
from messenger.shared.domain.errors import DomainError
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
InvalidChatData: ("invalid_request", 400),
InvalidMessageText: ("invalid_request", 400),
InvalidPageRequest: ("invalid_request", 400),
InvalidAttachmentList: ("invalid_request", 400),
ChatNotFound: ("not_found", 404),
UnknownAttachment: ("not_found", 404),
IdempotencyConflict: ("conflict", 409),
}
@@ -0,0 +1,90 @@
from typing import Annotated
from uuid import UUID
from dishka.integrations.fastapi import FromDishka, inject
from fastapi import APIRouter, Query, status
from messenger.messaging.application.bus import MessagingCommandBus
from messenger.messaging.application.commands import CreateChat, PostMessage
from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory
from messenger.messaging.entrypoints.schemas import (
ChatOut,
CreateChatRequest,
CreateMessageRequest,
IdempotencyKey,
MessageOut,
PageOut,
PageQuery,
)
from messenger.shared.entrypoints.actor import Actor
chats_router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
messages_router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
@chats_router.post("", status_code=status.HTTP_201_CREATED)
@inject
async def create_chat(
actor: Actor,
body: CreateChatRequest,
bus: FromDishka[MessagingCommandBus],
) -> ChatOut:
chat = await bus.execute(
CreateChat(creator_id=actor, title=body.title, member_ids=body.member_ids)
)
return ChatOut.of(chat)
@chats_router.get("")
@inject
async def list_chats(
actor: Actor,
page: Annotated[PageQuery, Query()],
query: FromDishka[ListChats],
) -> PageOut[ChatOut]:
chats = await query(actor, limit=page.limit, cursor=page.cursor)
return PageOut[ChatOut].of(chats, ChatOut.of)
@chats_router.get("/{chat_id}")
@inject
async def read_chat(
chat_id: UUID,
actor: Actor,
query: FromDishka[GetChat],
) -> ChatOut:
return ChatOut.of(await query(chat_id, actor))
@messages_router.post("", status_code=status.HTTP_201_CREATED)
@inject
async def post_message(
chat_id: UUID,
actor: Actor,
body: CreateMessageRequest,
key: IdempotencyKey,
bus: FromDishka[MessagingCommandBus],
) -> MessageOut:
message = await bus.execute(
PostMessage(
sender_id=actor,
chat_id=chat_id,
text=body.text,
key=key,
fingerprint=body.fingerprint(),
attachment_ids=tuple(body.attachment_ids),
)
)
return MessageOut.of(message)
@messages_router.get("")
@inject
async def read_history(
chat_id: UUID,
actor: Actor,
page: Annotated[PageQuery, Query()],
query: FromDishka[ReadHistory],
) -> PageOut[MessageOut]:
messages = await query(chat_id, actor, limit=page.limit, cursor=page.cursor)
return PageOut[MessageOut].of(messages, MessageOut.of)
@@ -0,0 +1,69 @@
from datetime import timedelta
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.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,
PostgresMessagingUnitOfWork,
)
from messenger.shared.application.commands import Command
from messenger.shared.application.messagebus import CommandHandler
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator
from messenger.shared.infrastructure.postgres import Database
class MessagingProvider(Provider):
def __init__(self, settings: MessagingSettings) -> None:
super().__init__()
self._settings = settings
@provide(scope=Scope.APP)
def settings(self) -> MessagingSettings:
return self._settings
@provide(scope=Scope.APP)
def directory(self, database: Database) -> ChatDirectory:
return PostgresChatDirectory(database)
@provide(scope=Scope.APP)
def cursors(self, settings: MessagingSettings) -> CursorCodec:
return SignedCursorCodec(settings.cursor_secret.get_secret_value().encode())
@provide(scope=Scope.REQUEST)
def unit_of_work(self, database: Database) -> MessagingUnitOfWork:
return PostgresMessagingUnitOfWork(database)
@provide(scope=Scope.REQUEST)
def chat(self, directory: ChatDirectory) -> GetChat:
return GetChat(directory)
@provide(scope=Scope.REQUEST)
def chat_list(self, directory: ChatDirectory, cursors: CursorCodec) -> ListChats:
return ListChats(directory, cursors)
@provide(scope=Scope.REQUEST)
def history(self, directory: ChatDirectory, cursors: CursorCodec) -> ReadHistory:
return ReadHistory(directory, cursors)
@provide(scope=Scope.REQUEST)
def command_bus(
self,
uow: MessagingUnitOfWork,
publisher: EventPublisher,
clock: Clock,
ids: IdGenerator,
settings: MessagingSettings,
) -> MessagingCommandBus:
ttl = timedelta(seconds=settings.idempotency_ttl_seconds)
handlers: dict[type[Command], CommandHandler] = {
CreateChat: CreateChatHandler(uow, clock, ids),
PostMessage: PostMessageHandler(uow, clock, ids, ttl),
}
return MessagingCommandBus(handlers, uow, publisher)
@@ -0,0 +1,27 @@
from messenger.messaging.domain.events import ChatCreated, MessagePosted
from messenger.shared.application.ports import Logger
LOG_FIELDS = frozenset({"chat_id", "message_id", "count"})
class MessagingJournal:
__slots__ = ("_logger",)
def __init__(self, logger: Logger) -> None:
self._logger = logger
async def on_chat_created(self, event: ChatCreated) -> None:
self._logger.info(
"audit.chat_created",
chat_id=str(event.chat_id),
actor_id=str(event.creator_id),
count=event.member_count,
)
async def on_message_posted(self, event: MessagePosted) -> None:
self._logger.info(
"audit.message_posted",
chat_id=str(event.chat_id),
actor_id=str(event.sender_id),
message_id=str(event.message_id),
)
@@ -0,0 +1,85 @@
from collections.abc import Callable
from datetime import datetime
from hashlib import sha256
from typing import Annotated, Self
from uuid import UUID
from fastapi import Header
from pydantic import BaseModel, ConfigDict, Field
from messenger.messaging.application.queries import Page
from messenger.messaging.domain.models import Chat, Message
STRICT = ConfigDict(extra="forbid", strict=True)
type IdempotencyKey = Annotated[
str,
Header(alias="Idempotency-Key", min_length=1, max_length=128, pattern=r"^[A-Za-z0-9._:-]+$"),
]
class CreateChatRequest(BaseModel):
model_config = STRICT
title: str
member_ids: list[Annotated[UUID, Field(strict=False)]]
class CreateMessageRequest(BaseModel):
model_config = STRICT
text: str
attachment_ids: list[Annotated[UUID, Field(strict=False)]] = Field(default_factory=list)
def fingerprint(self) -> bytes:
return sha256(self.model_dump_json().encode()).digest()
class PageQuery(BaseModel):
limit: int = Field(default=50, ge=1, le=100)
cursor: str | None = None
class ChatOut(BaseModel):
id: UUID
title: str
member_ids: tuple[UUID, ...]
created_at: datetime
@classmethod
def of(cls, chat: Chat) -> ChatOut:
return cls(
id=chat.id,
title=chat.title.value,
member_ids=chat.member_ids,
created_at=chat.created_at,
)
class MessageOut(BaseModel):
id: UUID
chat_id: UUID
sender_id: UUID
text: str
created_at: datetime
attachment_ids: tuple[UUID, ...]
@classmethod
def of(cls, message: Message) -> MessageOut:
return cls(
id=message.id,
chat_id=message.chat_id,
sender_id=message.sender_id,
text=message.text.value,
created_at=message.created_at,
attachment_ids=message.attachment_ids,
)
class PageOut[ItemT](BaseModel):
items: list[ItemT]
next_cursor: str | None
@classmethod
def of[SourceT](cls, page: Page[SourceT], view: Callable[[SourceT], ItemT]) -> Self:
return cls(items=[view(item) for item in page.items], next_cursor=page.next_cursor)