feat: add image attachments to messages
- upload, metadata and download endpoints for PNG/JPEG attachments:
limits before reading and decompression, type by content,
structural integrity check without decoding pixels, safe filename
- write order: pending row with object key -> PUT to S3 -> ready;
per-step DB sessions so no pool connection is held during transfers
- attachment_ids in messages (validation, idempotency hash, history);
whitespace-only text allowed with an attachment (teacher, 2026-10-20)
- migration: attachments and message_attachments tables, text length
CHECK relaxed with NOT VALID
- student tests, fault checks and driver commands for attachments;
rollout profile starts from e1161f7 and checks the commit first
- sync attachments deltas into main specs; rules, AGENTS.md, PLAN.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,10 @@
|
||||
from .attachment import (
|
||||
AttachmentContentMissing,
|
||||
AttachmentNotFound,
|
||||
PayloadTooLarge,
|
||||
UnsupportedMediaType,
|
||||
UploadInterrupted,
|
||||
)
|
||||
from .base import DomainError
|
||||
from .chat import ChatNotFound, InvalidChatMembers
|
||||
from .idempotency import IdempotencyConflict
|
||||
@@ -8,6 +15,8 @@ from .storage import ObjectStorageUnavailable, StoredObjectMissing
|
||||
from .user import UsernameTaken
|
||||
|
||||
__all__ = [
|
||||
"AttachmentContentMissing",
|
||||
"AttachmentNotFound",
|
||||
"ChatNotFound",
|
||||
"DomainError",
|
||||
"IdempotencyConflict",
|
||||
@@ -15,8 +24,11 @@ __all__ = [
|
||||
"InvalidCredentials",
|
||||
"InvalidCursor",
|
||||
"ObjectStorageUnavailable",
|
||||
"PayloadTooLarge",
|
||||
"ServiceUnavailable",
|
||||
"StoredObjectMissing",
|
||||
"Unauthenticated",
|
||||
"UnsupportedMediaType",
|
||||
"UploadInterrupted",
|
||||
"UsernameTaken",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
from .base import DomainError
|
||||
|
||||
|
||||
class AttachmentNotFound(DomainError):
|
||||
"""Вложения нет, оно чужое или ещё не готово (`pending`).
|
||||
|
||||
Все случаи — одно исключение и одинаковый 404: ответ не раскрывает
|
||||
существование чужого вложения.
|
||||
"""
|
||||
|
||||
default_message = "Not found"
|
||||
|
||||
|
||||
class PayloadTooLarge(DomainError):
|
||||
"""Тело больше 10 MiB или изображение больше 40 млн пикселей."""
|
||||
|
||||
default_message = "Payload too large"
|
||||
|
||||
|
||||
class UnsupportedMediaType(DomainError):
|
||||
"""Не PNG и не JPEG, подмена MIME или повреждённое изображение."""
|
||||
|
||||
default_message = "Unsupported media type"
|
||||
|
||||
|
||||
class UploadInterrupted(DomainError):
|
||||
"""Клиент оборвал передачу тела загрузки."""
|
||||
|
||||
default_message = "Upload interrupted"
|
||||
|
||||
|
||||
class AttachmentContentMissing(DomainError):
|
||||
"""У готового вложения нет объекта в S3 или его размер другой.
|
||||
|
||||
Расхождение хранилищ, а не ошибка клиента: 500 без деталей, причина —
|
||||
в журнале сервиса.
|
||||
"""
|
||||
|
||||
default_message = "Internal server error"
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Метаданные вложений в PostgreSQL.
|
||||
|
||||
Строка пишется в статусе `pending` до записи объекта и переводится в
|
||||
`ready` после неё (design change `attachments`, решение 1). Видимость
|
||||
`pending` решает сервис: repo отдаёт строку как есть.
|
||||
"""
|
||||
|
||||
from collections.abc import Collection
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import Row, insert, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.infra.db.models import Attachment
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import AttachmentStatus, ImageType
|
||||
|
||||
_ATTACHMENT_COLUMNS = (
|
||||
Attachment.id,
|
||||
Attachment.chat_id,
|
||||
Attachment.owner_id,
|
||||
Attachment.filename,
|
||||
Attachment.content_type,
|
||||
Attachment.size_bytes,
|
||||
Attachment.sha256,
|
||||
Attachment.object_key,
|
||||
Attachment.status,
|
||||
Attachment.created_at,
|
||||
Attachment.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _to_dto(row: Row) -> dataclasses.AttachmentFullDTO:
|
||||
fields = dict(row._mapping)
|
||||
fields["content_type"] = ImageType(fields["content_type"])
|
||||
fields["status"] = AttachmentStatus(fields["status"])
|
||||
return dataclasses.AttachmentFullDTO(**fields)
|
||||
|
||||
|
||||
async def insert_attachment(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
attachment: dataclasses.AttachmentFullDTO,
|
||||
) -> dataclasses.AttachmentFullDTO:
|
||||
"""Строка вложения со всеми колонками DTO."""
|
||||
await db_session.execute(
|
||||
insert(Attachment).values(
|
||||
id=attachment.id,
|
||||
chat_id=attachment.chat_id,
|
||||
owner_id=attachment.owner_id,
|
||||
filename=attachment.filename,
|
||||
content_type=attachment.content_type.value,
|
||||
size_bytes=attachment.size_bytes,
|
||||
sha256=attachment.sha256,
|
||||
object_key=attachment.object_key,
|
||||
status=attachment.status.value,
|
||||
created_at=attachment.created_at,
|
||||
updated_at=attachment.updated_at,
|
||||
),
|
||||
)
|
||||
return attachment
|
||||
|
||||
|
||||
async def mark_ready(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
updated_at: datetime,
|
||||
) -> dataclasses.AttachmentFullDTO | None:
|
||||
"""`pending` → `ready`; `None` — строки в статусе `pending` нет."""
|
||||
statement = (
|
||||
update(Attachment)
|
||||
.where(
|
||||
Attachment.id == attachment_id,
|
||||
Attachment.status == AttachmentStatus.PENDING.value,
|
||||
)
|
||||
.values(status=AttachmentStatus.READY.value, updated_at=updated_at)
|
||||
.returning(*_ATTACHMENT_COLUMNS)
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def get_attachment(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
) -> dataclasses.AttachmentFullDTO | None:
|
||||
statement = select(*_ATTACHMENT_COLUMNS).where(
|
||||
Attachment.id == attachment_id,
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def get_attachments(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
attachment_ids: Collection[UUID],
|
||||
) -> list[dataclasses.AttachmentFullDTO]:
|
||||
"""Найденные строки по первичному ключу, в любом порядке."""
|
||||
statement = select(*_ATTACHMENT_COLUMNS).where(
|
||||
Attachment.id.in_(attachment_ids),
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Оригинал вложения в S3: ключ объекта и операции над ним.
|
||||
|
||||
Repo над хранилищем объектов, как `chat_cache.py` над Valkey: первый
|
||||
параметр — `storage`, один вызов на функцию. Ключ —
|
||||
`<имя базы>/attachments/<id>/original` (design change `attachments`,
|
||||
решение 4): назначает сервер, `filename` в него не входит; объекты
|
||||
`make test_isolated` лежат под `test_<db>/`. Ключ хранится в строке
|
||||
вложения и при чтении берётся оттуда.
|
||||
"""
|
||||
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from uuid import UUID
|
||||
|
||||
from src.infra.s3 import ObjectStorage, StoredObject
|
||||
from src.utils.constants import (
|
||||
ATTACHMENT_KEY_PREFIX,
|
||||
ATTACHMENT_ORIGINAL_SUFFIX,
|
||||
S3_KEY_SEPARATOR,
|
||||
)
|
||||
|
||||
|
||||
def original_key(storage: ObjectStorage, *, attachment_id: UUID) -> str:
|
||||
return S3_KEY_SEPARATOR.join(
|
||||
(
|
||||
storage.namespace,
|
||||
ATTACHMENT_KEY_PREFIX,
|
||||
str(attachment_id),
|
||||
ATTACHMENT_ORIGINAL_SUFFIX,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def put_original(
|
||||
storage: ObjectStorage,
|
||||
*,
|
||||
key: str,
|
||||
data: bytes,
|
||||
content_type: str,
|
||||
) -> None:
|
||||
await storage.put(key, data, content_type=content_type)
|
||||
|
||||
|
||||
def open_original(
|
||||
storage: ObjectStorage,
|
||||
*,
|
||||
key: str,
|
||||
) -> AbstractAsyncContextManager[StoredObject]:
|
||||
"""Объект на чтение блоками; нет объекта — `StoredObjectMissing`."""
|
||||
return storage.open(key)
|
||||
@@ -12,7 +12,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.repos.message import MESSAGE_COLUMNS
|
||||
from src.core.repos.message import MESSAGE_COLUMNS, to_message_dto
|
||||
from src.infra.db.models import IdempotencyKey, Message
|
||||
from src.schemas import dataclasses
|
||||
|
||||
@@ -69,7 +69,8 @@ async def get_key_result(
|
||||
chat_id: UUID,
|
||||
key: str,
|
||||
) -> dataclasses.IdempotencyRecordDTO | None:
|
||||
"""Хэш тела и сообщение, сохранённые под ключом; None — ключа нет."""
|
||||
"""Хэш тела и сообщение с вложениями, сохранённые под ключом; None —
|
||||
ключа нет."""
|
||||
statement = (
|
||||
select(IdempotencyKey.request_hash, *MESSAGE_COLUMNS)
|
||||
.join(Message, Message.id == IdempotencyKey.message_id)
|
||||
@@ -82,9 +83,7 @@ async def get_key_result(
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
fields = dict(row._mapping)
|
||||
request_hash = fields.pop("request_hash")
|
||||
return dataclasses.IdempotencyRecordDTO(
|
||||
request_hash=request_hash,
|
||||
message=dataclasses.MessageFullDTO(**fields),
|
||||
request_hash=row.request_hash,
|
||||
message=to_message_dto(row._mapping),
|
||||
)
|
||||
|
||||
@@ -1,13 +1,27 @@
|
||||
from dataclasses import asdict
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import insert, select, tuple_
|
||||
from sqlalchemy import Uuid, func, insert, select, tuple_
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.infra.db.models import Message
|
||||
from src.infra.db.models import Message, MessageAttachment
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import CursorKey
|
||||
|
||||
# вложения сообщения в порядке отправки: коррелированный подзапрос по
|
||||
# первичному ключу `(message_id, position)` на каждую строку страницы,
|
||||
# индекс истории прежний (design change `attachments`, решение 8). Нет
|
||||
# вложений — пустой массив, а не NULL
|
||||
_ATTACHMENT_IDS = func.array(
|
||||
select(MessageAttachment.attachment_id)
|
||||
.where(MessageAttachment.message_id == Message.id)
|
||||
.order_by(MessageAttachment.position)
|
||||
.scalar_subquery(),
|
||||
type_=ARRAY(Uuid()),
|
||||
).label("attachment_ids")
|
||||
|
||||
# колонки MessageFullDTO; их же выбирает чтение сохранённого результата
|
||||
# ключа идемпотентности
|
||||
MESSAGE_COLUMNS = (
|
||||
@@ -16,23 +30,72 @@ MESSAGE_COLUMNS = (
|
||||
Message.sender_id,
|
||||
Message.text,
|
||||
Message.created_at,
|
||||
_ATTACHMENT_IDS,
|
||||
)
|
||||
|
||||
|
||||
def to_message_dto(fields: Mapping[str, Any]) -> dataclasses.MessageFullDTO:
|
||||
"""DTO из колонок `MESSAGE_COLUMNS`."""
|
||||
return dataclasses.MessageFullDTO(
|
||||
id=fields["id"],
|
||||
chat_id=fields["chat_id"],
|
||||
sender_id=fields["sender_id"],
|
||||
text=fields["text"],
|
||||
created_at=fields["created_at"],
|
||||
attachment_ids=tuple(fields["attachment_ids"]),
|
||||
)
|
||||
|
||||
|
||||
async def insert_message(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
instance_id: str,
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
"""Вставка сообщения; `instance_id` — реплика, которая его записала
|
||||
(колонка только для диагностики, в DTO и ответ не попадает)."""
|
||||
"""Строка сообщения; `instance_id` — реплика, которая его записала
|
||||
(колонка только для диагностики, в DTO и ответ не попадает). Связи с
|
||||
вложениями пишет `insert_message_attachments`."""
|
||||
await db_session.execute(
|
||||
insert(Message).values(**asdict(message), instance_id=instance_id),
|
||||
insert(Message).values(
|
||||
id=message.id,
|
||||
chat_id=message.chat_id,
|
||||
sender_id=message.sender_id,
|
||||
text=message.text,
|
||||
created_at=message.created_at,
|
||||
instance_id=instance_id,
|
||||
),
|
||||
)
|
||||
return message
|
||||
|
||||
|
||||
async def insert_message_attachments(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
) -> int:
|
||||
"""Все связи одной вставкой; `position` — место в `attachment_ids`.
|
||||
|
||||
Вызывается только с непустым `attachment_ids`. `created_at` связи —
|
||||
время сообщения.
|
||||
"""
|
||||
result = await db_session.execute(
|
||||
insert(MessageAttachment).values(
|
||||
[
|
||||
{
|
||||
"message_id": message.id,
|
||||
"position": position,
|
||||
"attachment_id": attachment_id,
|
||||
"created_at": message.created_at,
|
||||
}
|
||||
for position, attachment_id in enumerate(
|
||||
message.attachment_ids,
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
return result.rowcount
|
||||
|
||||
|
||||
async def get_chat_messages_page(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
@@ -56,4 +119,4 @@ async def get_chat_messages_page(
|
||||
tuple_(Message.created_at, Message.id) > tuple_(*after),
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [dataclasses.MessageFullDTO(**row._mapping) for row in rows]
|
||||
return [to_message_dto(row._mapping) for row in rows]
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from .attachment import AttachmentService
|
||||
from .chat import ChatService
|
||||
from .message import MessageService
|
||||
from .session import SessionService
|
||||
from .user import UserService
|
||||
|
||||
__all__ = [
|
||||
"AttachmentService",
|
||||
"ChatService",
|
||||
"MessageService",
|
||||
"SessionService",
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import hashlib
|
||||
import time
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
from contextlib import AbstractAsyncContextManager, AsyncExitStack
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import anyio.to_thread
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core import exceptions
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.repos import attachment_object as attachment_object_repo
|
||||
from src.core.services.chat import ChatService
|
||||
from src.infra.cache import Cache
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.s3 import ObjectStorage
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import AttachmentStatus, ImageType
|
||||
from src.utils.constants import ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_PIXELS
|
||||
from src.utils.image import (
|
||||
DamagedImage,
|
||||
ImageInfo,
|
||||
TooManyPixels,
|
||||
UnsupportedImage,
|
||||
inspect_image,
|
||||
)
|
||||
from src.utils.utc import utcnow
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="attachment_service")
|
||||
|
||||
# Content-Type загрузки: тип без параметров, в нижнем регистре
|
||||
_ACCEPTED_MEDIA_TYPES = frozenset(image_type.value for image_type in ImageType)
|
||||
|
||||
# короткая сессия БД на один шаг: `db_session_scope` слоя API
|
||||
type DbScope = Callable[[], AbstractAsyncContextManager[AsyncSession]]
|
||||
|
||||
|
||||
def _inspect(data: bytes) -> tuple[ImageInfo, bytes]:
|
||||
"""Структура изображения и SHA-256 — одним вызовом в потоке."""
|
||||
info = inspect_image(data, max_pixels=ATTACHMENT_MAX_PIXELS)
|
||||
return info, hashlib.sha256(data).digest()
|
||||
|
||||
|
||||
class AttachmentService:
|
||||
"""Вложения: загрузка в S3 с метаданными в PostgreSQL, чтение, отдача.
|
||||
|
||||
Сессии на весь запрос нет: каждый шаг с БД — свой короткий
|
||||
`async with self.db_scope()`, без вложенных, поэтому ни одно
|
||||
соединение пула не занято передачей тела (design change
|
||||
`attachments`, решение 5). `filename` в журнал не пишется.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
db_scope: DbScope,
|
||||
cache: Cache,
|
||||
storage: ObjectStorage,
|
||||
) -> None:
|
||||
self.db_scope = db_scope
|
||||
self.cache = cache
|
||||
self.storage = storage
|
||||
|
||||
async def _require_member(
|
||||
self,
|
||||
*,
|
||||
db_session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> None:
|
||||
await ChatService(
|
||||
db_session=db_session,
|
||||
cache=self.cache,
|
||||
).get_chat_for_member(chat_id=chat_id, user_id=user_id)
|
||||
|
||||
async def upload(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: str,
|
||||
media_type: str | None,
|
||||
content_length: int | None,
|
||||
body: AsyncIterator[bytes],
|
||||
) -> dataclasses.AttachmentFullDTO:
|
||||
"""Загрузка оригинала; 201 только после `ready` в БД.
|
||||
|
||||
Порядок проверок — спек «Порядок проверок загрузки»: членство
|
||||
(404), `Content-Type` (415), `Content-Length` (413), затем тело со
|
||||
счётчиком (413) и содержимое (415 или 413). Порядок записи
|
||||
(решение 1): строка `pending` с ключом объекта — commit, PUT,
|
||||
`ready` — commit. Отказ S3 или БД после строки `pending` — 503,
|
||||
строка остаётся до уборщика (`upload-consistency`).
|
||||
"""
|
||||
started = time.monotonic()
|
||||
log = logger.bind(
|
||||
method="upload",
|
||||
chat_id=chat_id,
|
||||
filename_length=len(filename),
|
||||
)
|
||||
async with self.db_scope() as db_session:
|
||||
await self._require_member(
|
||||
db_session=db_session,
|
||||
chat_id=chat_id,
|
||||
user_id=owner_id,
|
||||
)
|
||||
if media_type not in _ACCEPTED_MEDIA_TYPES:
|
||||
log.info("Rejected attachment", reason="type")
|
||||
raise exceptions.UnsupportedMediaType
|
||||
if (
|
||||
content_length is not None
|
||||
and content_length > ATTACHMENT_MAX_BYTES
|
||||
):
|
||||
log.info(
|
||||
"Rejected attachment",
|
||||
reason="declared_size",
|
||||
declared_size=content_length,
|
||||
)
|
||||
raise exceptions.PayloadTooLarge
|
||||
data = await self._read_body(body=body, log=log)
|
||||
try:
|
||||
info, sha256 = await anyio.to_thread.run_sync(_inspect, data)
|
||||
except TooManyPixels as e:
|
||||
log.info("Rejected attachment", reason="pixels")
|
||||
raise exceptions.PayloadTooLarge from e
|
||||
except DamagedImage as e:
|
||||
log.info("Rejected attachment", reason="damaged")
|
||||
raise exceptions.UnsupportedMediaType from e
|
||||
except UnsupportedImage as e:
|
||||
log.info("Rejected attachment", reason="content")
|
||||
raise exceptions.UnsupportedMediaType from e
|
||||
if info.content_type != media_type:
|
||||
log.info("Rejected attachment", reason="content_mismatch")
|
||||
raise exceptions.UnsupportedMediaType
|
||||
|
||||
attachment_id = uuid4()
|
||||
now = utcnow()
|
||||
pending = dataclasses.AttachmentFullDTO(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
content_type=info.content_type,
|
||||
size_bytes=len(data),
|
||||
sha256=sha256,
|
||||
object_key=attachment_object_repo.original_key(
|
||||
self.storage,
|
||||
attachment_id=attachment_id,
|
||||
),
|
||||
status=AttachmentStatus.PENDING,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
async with self.db_scope() as db_session:
|
||||
await attachment_repo.insert_attachment(
|
||||
db_session=db_session,
|
||||
attachment=pending,
|
||||
)
|
||||
await db_session.commit()
|
||||
await attachment_object_repo.put_original(
|
||||
self.storage,
|
||||
key=pending.object_key,
|
||||
data=data,
|
||||
content_type=pending.content_type.value,
|
||||
)
|
||||
async with self.db_scope() as db_session:
|
||||
ready = await attachment_repo.mark_ready(
|
||||
db_session=db_session,
|
||||
attachment_id=attachment_id,
|
||||
updated_at=utcnow(),
|
||||
)
|
||||
await db_session.commit()
|
||||
if ready is None:
|
||||
# строку pending удалить некому, пока нет уборщика: ветку
|
||||
# переопределит change upload-consistency
|
||||
raise RuntimeError("Pending attachment disappeared before ready")
|
||||
log.info(
|
||||
"Uploaded attachment",
|
||||
attachment_id=attachment_id,
|
||||
size_bytes=ready.size_bytes,
|
||||
content_type=ready.content_type,
|
||||
width=info.width,
|
||||
height=info.height,
|
||||
duration_ms=round((time.monotonic() - started) * 1000),
|
||||
)
|
||||
return ready
|
||||
|
||||
async def _read_body(
|
||||
self,
|
||||
*,
|
||||
body: AsyncIterator[bytes],
|
||||
log: AbstractLogger,
|
||||
) -> bytes:
|
||||
"""Тело целиком; больше лимита — 413 сразу, без дочитывания."""
|
||||
buffer = bytearray()
|
||||
try:
|
||||
async for chunk in body:
|
||||
if len(buffer) + len(chunk) > ATTACHMENT_MAX_BYTES:
|
||||
log.info(
|
||||
"Rejected attachment",
|
||||
reason="size",
|
||||
size=len(buffer) + len(chunk),
|
||||
)
|
||||
raise exceptions.PayloadTooLarge
|
||||
buffer += chunk
|
||||
except exceptions.UploadInterrupted:
|
||||
log.info("Rejected attachment", reason="interrupted")
|
||||
raise
|
||||
return bytes(buffer)
|
||||
|
||||
async def get_attachment(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dataclasses.AttachmentFullDTO:
|
||||
"""Готовое вложение для участника его чата; иначе 404.
|
||||
|
||||
Нет строки, она `pending` или пользователь не участник —
|
||||
одинаковый `AttachmentNotFound`.
|
||||
"""
|
||||
async with self.db_scope() as db_session:
|
||||
attachment = await attachment_repo.get_attachment(
|
||||
db_session=db_session,
|
||||
attachment_id=attachment_id,
|
||||
)
|
||||
if (
|
||||
attachment is None
|
||||
or attachment.status != AttachmentStatus.READY
|
||||
):
|
||||
raise exceptions.AttachmentNotFound
|
||||
try:
|
||||
await self._require_member(
|
||||
db_session=db_session,
|
||||
chat_id=attachment.chat_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
except exceptions.ChatNotFound as e:
|
||||
raise exceptions.AttachmentNotFound from e
|
||||
return attachment
|
||||
|
||||
async def open_content(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dataclasses.AttachmentContentDTO:
|
||||
"""Оригинал потоком из S3 (решение 7).
|
||||
|
||||
Отказ S3 — 503 до заголовков ответа. Нет объекта или размер в S3
|
||||
другой — `error` в журнале и 500; строку сервис не меняет.
|
||||
"""
|
||||
attachment = await self.get_attachment(
|
||||
attachment_id=attachment_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
log = logger.bind(
|
||||
method="open_content",
|
||||
attachment_id=attachment_id,
|
||||
object_key=attachment.object_key,
|
||||
)
|
||||
stack = AsyncExitStack()
|
||||
try:
|
||||
stored = await stack.enter_async_context(
|
||||
attachment_object_repo.open_original(
|
||||
self.storage,
|
||||
key=attachment.object_key,
|
||||
),
|
||||
)
|
||||
except exceptions.StoredObjectMissing as e:
|
||||
log.error("Attachment content is missing")
|
||||
raise exceptions.AttachmentContentMissing from e
|
||||
if stored.size != attachment.size_bytes:
|
||||
await stack.aclose()
|
||||
log.error(
|
||||
"Attachment content size differs",
|
||||
size_bytes=attachment.size_bytes,
|
||||
stored_size=stored.size,
|
||||
)
|
||||
raise exceptions.AttachmentContentMissing
|
||||
|
||||
async def chunks() -> AsyncIterator[bytes]:
|
||||
try:
|
||||
async for chunk in stored.iter_chunks():
|
||||
yield chunk
|
||||
finally:
|
||||
await stack.aclose()
|
||||
|
||||
return dataclasses.AttachmentContentDTO(
|
||||
content_type=attachment.content_type,
|
||||
size_bytes=attachment.size_bytes,
|
||||
chunks=chunks(),
|
||||
close=stack.aclose,
|
||||
)
|
||||
@@ -1,5 +1,6 @@
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Sequence
|
||||
from datetime import timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
@@ -7,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.repos import idempotency as idempotency_repo
|
||||
from src.core.repos import message as message_repo
|
||||
from src.core.services.chat import ChatService
|
||||
@@ -14,22 +16,33 @@ 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) -> bytes:
|
||||
def message_request_hash(
|
||||
*,
|
||||
text: str,
|
||||
attachment_ids: Sequence[UUID] = (),
|
||||
) -> bytes:
|
||||
"""SHA-256 канонического JSON тела отправки сообщения.
|
||||
|
||||
Тело собирается из аргументов сервиса, то есть уже разобранное:
|
||||
пробелы, экранирование и порядок полей запроса на хэш не влияют. Новое
|
||||
поле тела (с лабы 4 — `attachment_ids`) добавляется сюда со
|
||||
значением по умолчанию, чтобы отсутствующее поле равнялось явному.
|
||||
пробелы, экранирование и порядок полей запроса на хэш не влияют.
|
||||
`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(
|
||||
{"text": text},
|
||||
body,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
@@ -54,15 +67,22 @@ class MessageService:
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
idempotency_key: str,
|
||||
attachment_ids: Sequence[UUID] = (),
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
"""Отправка с ключом идемпотентности.
|
||||
|
||||
Ключ и сообщение пишутся одной транзакцией, ключ — первым. Повтор
|
||||
того же тела возвращает сохранённое сообщение, другое тело —
|
||||
`IdempotencyConflict` (design change `instance-id-idempotency`,
|
||||
решения 2–5). Ключ не логируется.
|
||||
Ключ, сообщение и его связи с вложениями пишутся одной
|
||||
транзакцией, ключ — первым. Повтор того же тела возвращает
|
||||
сохранённое сообщение, другое тело — `IdempotencyConflict`
|
||||
(design change `instance-id-idempotency`, решения 2–5). Вложения
|
||||
проверяются до захвата ключа: ошибка его не занимает (design
|
||||
change `attachments`, решение 8). Ключ не логируется.
|
||||
"""
|
||||
log = logger.bind(method="send_message", chat_id=chat_id)
|
||||
log = logger.bind(
|
||||
method="send_message",
|
||||
chat_id=chat_id,
|
||||
attachments_count=len(attachment_ids),
|
||||
)
|
||||
# состав чата не меняется, поэтому проверка членства (в том числе
|
||||
# по кэшу) не устареет; составные внешние ключи сообщения и ключа
|
||||
# идемпотентности — страховка на уровне БД. Повтор проходит её
|
||||
@@ -71,14 +91,24 @@ class MessageService:
|
||||
chat_id=chat_id,
|
||||
user_id=sender_id,
|
||||
)
|
||||
if attachment_ids:
|
||||
await self._require_ready_attachments(
|
||||
chat_id=chat_id,
|
||||
attachment_ids=attachment_ids,
|
||||
log=log,
|
||||
)
|
||||
now = utcnow()
|
||||
request_hash = message_request_hash(text=text)
|
||||
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 idempotency_repo.claim_key(
|
||||
db_session=self.db_session,
|
||||
@@ -97,6 +127,11 @@ class MessageService:
|
||||
message=message,
|
||||
instance_id=settings.app.instance_id,
|
||||
)
|
||||
if attachment_ids:
|
||||
await message_repo.insert_message_attachments(
|
||||
db_session=self.db_session,
|
||||
message=message,
|
||||
)
|
||||
# отложенная проверка ссылки ключа на сообщение — здесь
|
||||
await self.db_session.commit()
|
||||
log.info(
|
||||
@@ -128,6 +163,34 @@ class MessageService:
|
||||
)
|
||||
return saved.message
|
||||
|
||||
async def _require_ready_attachments(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
attachment_ids: Sequence[UUID],
|
||||
log: AbstractLogger,
|
||||
) -> None:
|
||||
"""Каждое вложение — готовое вложение этого чата; иначе 404.
|
||||
|
||||
Неизвестное, другого чата и `pending` неразличимы. Чат вложения не
|
||||
меняется, а `ready` не откатывается, поэтому проверка в этой же
|
||||
транзакции не устареет до commit; существование держит ещё и
|
||||
внешний ключ связи.
|
||||
"""
|
||||
found = await attachment_repo.get_attachments(
|
||||
db_session=self.db_session,
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
ready = {
|
||||
attachment.id
|
||||
for attachment in found
|
||||
if attachment.chat_id == chat_id
|
||||
and attachment.status == AttachmentStatus.READY
|
||||
}
|
||||
if not ready.issuperset(attachment_ids):
|
||||
log.info("Rejected message attachments")
|
||||
raise exceptions.AttachmentNotFound
|
||||
|
||||
async def list_messages(
|
||||
self,
|
||||
*,
|
||||
|
||||
Reference in New Issue
Block a user