forked from mtusi2026/mtusi2026lab7
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065. Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public tests, README, REPORT and evidence of lab 6 are not carried over; infra and scripts of the lab 7 skeleton stay as they are. Makefile is the lab 6 one with the lab 7 skeleton part restored (HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore are taken from lab 6 because both skeletons have the same files; .env.example is the lab 6 one without changes. The compose project, image and CI prefix are renamed to lab7, and references to the previous lab now name lab6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
221 lines
9.6 KiB
Python
221 lines
9.6 KiB
Python
import hashlib
|
|
import json
|
|
from collections.abc import Sequence
|
|
from datetime import timedelta
|
|
from uuid import UUID, uuid4
|
|
|
|
from src.config import settings
|
|
from src.core import exceptions
|
|
from src.core.ports.uow import AbstractUnitOfWork
|
|
from src.core.services.chat import require_member
|
|
from src.core.services.pagination import decode_page_cursor, split_page
|
|
from src.infra.cache import Cache
|
|
from src.infra.logger import AbstractLogger, get_logger
|
|
from src.schemas import dataclasses
|
|
from src.schemas.enums import AttachmentStatus
|
|
from src.utils.cursor import chat_messages_scope
|
|
from src.utils.utc import utcnow
|
|
|
|
logger: AbstractLogger = get_logger().bind(module="message_service")
|
|
|
|
|
|
def message_request_hash(
|
|
*,
|
|
text: str,
|
|
attachment_ids: Sequence[UUID] = (),
|
|
) -> bytes:
|
|
"""SHA-256 канонического JSON тела отправки сообщения.
|
|
|
|
Тело собирается из аргументов сервиса, то есть уже разобранное:
|
|
пробелы, экранирование и порядок полей запроса на хэш не влияют.
|
|
`attachment_ids` входит в тело только непустым: отсутствующее поле
|
|
равно `[]`, и ключ, сохранённый версией без вложений, повторяется
|
|
после замены реплик. id — `str(UUID)`, нижний регистр: регистр в
|
|
запросе хэш не меняет, порядок элементов меняет (design change
|
|
`attachments`, решение 9).
|
|
"""
|
|
body: dict[str, object] = {"text": text}
|
|
if attachment_ids:
|
|
body["attachment_ids"] = [str(item) for item in attachment_ids]
|
|
canonical = json.dumps(
|
|
body,
|
|
ensure_ascii=False,
|
|
sort_keys=True,
|
|
separators=(",", ":"),
|
|
)
|
|
return hashlib.sha256(canonical.encode()).digest()
|
|
|
|
|
|
class MessageService:
|
|
"""Сообщения; история не кэшируется, членство — по карточке чата."""
|
|
|
|
def __init__(self, uow: AbstractUnitOfWork, cache: Cache) -> None:
|
|
self.uow = uow
|
|
self.cache = cache
|
|
|
|
async def send_message(
|
|
self,
|
|
*,
|
|
chat_id: UUID,
|
|
sender_id: UUID,
|
|
text: str,
|
|
idempotency_key: str,
|
|
attachment_ids: Sequence[UUID] = (),
|
|
) -> dataclasses.MessageFullDTO:
|
|
"""Отправка с ключом идемпотентности.
|
|
|
|
Ключ, сообщение и его связи с вложениями пишутся одной
|
|
транзакцией, ключ — первым. Повтор того же тела возвращает
|
|
сохранённое сообщение, другое тело — `IdempotencyConflict`
|
|
(design change `instance-id-idempotency`, решения 2–5). Неизвестное,
|
|
чужое и `pending` вложение проверяются до захвата ключа: ошибка его
|
|
не занимает (design change `attachments`, решение 8). `failed` — после
|
|
захвата: повтор уже отправленного сообщения идёт по прежней ветке и на
|
|
текущее состояние вложения не смотрит, а новый ключ откатывается
|
|
вместе с транзакцией, и ответ 409 его не занимает (design change
|
|
`async-attachments`, решение 9). Ключ не логируется.
|
|
"""
|
|
log = logger.bind(
|
|
method="send_message",
|
|
chat_id=chat_id,
|
|
attachments_count=len(attachment_ids),
|
|
)
|
|
async with self.uow:
|
|
# состав чата не меняется, поэтому проверка членства (в том числе
|
|
# по кэшу) не устареет; составные внешние ключи сообщения и ключа
|
|
# идемпотентности — страховка на уровне БД. Повтор проходит её
|
|
# заново, как и проверку сессии в зависимости
|
|
await require_member(
|
|
self.uow,
|
|
self.cache,
|
|
chat_id=chat_id,
|
|
user_id=sender_id,
|
|
)
|
|
has_failed = False
|
|
if attachment_ids:
|
|
has_failed = await self._check_attachments(
|
|
chat_id=chat_id,
|
|
attachment_ids=attachment_ids,
|
|
log=log,
|
|
)
|
|
now = utcnow()
|
|
request_hash = message_request_hash(
|
|
text=text,
|
|
attachment_ids=attachment_ids,
|
|
)
|
|
message = dataclasses.MessageFullDTO(
|
|
id=uuid4(),
|
|
chat_id=chat_id,
|
|
sender_id=sender_id,
|
|
text=text,
|
|
created_at=now,
|
|
attachment_ids=tuple(attachment_ids),
|
|
)
|
|
claimed = await self.uow.idempotency.claim_key(
|
|
user_id=sender_id,
|
|
chat_id=chat_id,
|
|
key=idempotency_key,
|
|
request_hash=request_hash,
|
|
message_id=message.id,
|
|
created_at=now,
|
|
expired_before=now
|
|
- timedelta(seconds=settings.idempotency.ttl_seconds),
|
|
)
|
|
if claimed and has_failed:
|
|
# исключение внутри блока: новый ключ откатывается при выходе
|
|
log.info("Rejected message attachments", reason="failed")
|
|
raise exceptions.AttachmentFailed
|
|
if claimed:
|
|
await self.uow.messages.insert_message(
|
|
message=message,
|
|
instance_id=settings.app.instance_id,
|
|
)
|
|
if attachment_ids:
|
|
await self.uow.messages.insert_message_attachments(
|
|
message=message,
|
|
)
|
|
# отложенная проверка ссылки ключа на сообщение — здесь
|
|
await self.uow.commit()
|
|
log.info(
|
|
"Created message",
|
|
message_id=message.id,
|
|
text_length=len(text),
|
|
replayed=False,
|
|
)
|
|
return message
|
|
|
|
saved = await self.uow.idempotency.get_key_result(
|
|
user_id=sender_id,
|
|
chat_id=chat_id,
|
|
key=idempotency_key,
|
|
)
|
|
# снять блокировку строки ключа до ответа: её ждут повторы того же
|
|
# ключа, в том числе на других репликах
|
|
await self.uow.commit()
|
|
if saved is None:
|
|
# строку нашёл и заблокировал захват: пропасть она не могла
|
|
raise RuntimeError("Idempotency key disappeared after claim")
|
|
if saved.request_hash != request_hash:
|
|
raise exceptions.IdempotencyConflict
|
|
log.info(
|
|
"Replayed message",
|
|
message_id=saved.message.id,
|
|
replayed=True,
|
|
)
|
|
return saved.message
|
|
|
|
async def _check_attachments(
|
|
self,
|
|
*,
|
|
chat_id: UUID,
|
|
attachment_ids: Sequence[UUID],
|
|
log: AbstractLogger,
|
|
) -> bool:
|
|
"""Каждое вложение — принятое вложение этого чата; иначе 404. `True` —
|
|
среди них есть `failed`: решает ветка после захвата ключа.
|
|
|
|
Неизвестное, другого чата и `pending` неразличимы. `queued` и
|
|
`processing` можно: клиент узнает итог по метаданным. Вложение,
|
|
ставшее `failed` сразу после проверки, даст сообщение со ссылкой на
|
|
него — тот же итог, что и `failed` чуть позже отправки. Существование
|
|
держит ещё и внешний ключ связи.
|
|
"""
|
|
found = await self.uow.attachments.get_attachments(
|
|
attachment_ids=attachment_ids,
|
|
)
|
|
accepted = {
|
|
attachment.id: attachment.status
|
|
for attachment in found
|
|
if attachment.chat_id == chat_id
|
|
and attachment.status != AttachmentStatus.PENDING
|
|
}
|
|
if not accepted.keys() >= set(attachment_ids):
|
|
log.info("Rejected message attachments", reason="not_found")
|
|
raise exceptions.AttachmentNotFound
|
|
return AttachmentStatus.FAILED in accepted.values()
|
|
|
|
async def list_messages(
|
|
self,
|
|
*,
|
|
chat_id: UUID,
|
|
user_id: UUID,
|
|
limit: int,
|
|
cursor: str | None,
|
|
) -> dataclasses.MessagePageDTO:
|
|
scope = chat_messages_scope(chat_id)
|
|
async with self.uow:
|
|
await require_member(
|
|
self.uow,
|
|
self.cache,
|
|
chat_id=chat_id,
|
|
user_id=user_id,
|
|
)
|
|
after = decode_page_cursor(cursor, scope=scope)
|
|
rows = await self.uow.messages.get_chat_messages_page(
|
|
chat_id=chat_id,
|
|
after=after,
|
|
limit=limit,
|
|
)
|
|
items, next_cursor = split_page(rows, limit=limit, scope=scope)
|
|
return dataclasses.MessagePageDTO(items=items, next_cursor=next_cursor)
|