Лабораторная 4 - Костылев - БПИ2303 - На 5 #132
@@ -5,10 +5,10 @@
|
||||
|
||||
## 2. Зона `attachments`: домен и приложение
|
||||
|
||||
- [ ] 2.1 Домен: `Filename`, `ImageKind`, `ImageInfo`, агрегат `Attachment` (`stage` → `pending`, `store` → `ready` с событием `AttachmentStored`), ошибки зоны
|
||||
- [ ] 2.2 Порты: `ChatMembership`, `ObjectStorage` (`put`/`open`/`delete`, `ObjectContent`, `ObjectMissing`), `ImageInspector`, `AttachmentsUnitOfWork`, `AttachmentDirectory`
|
||||
- [ ] 2.3 Команда `UploadAttachment` и обработчик: членство → имя → `Content-Type` → поток со счётчиком и SHA-256 → проверка изображения → `pending` → `put` → `ready`; запросы `GetAttachment`, `OpenAttachment`
|
||||
- [ ] 2.4 Проверка группы: unit-тесты `Filename` (граничные и опасные имена), агрегата и порядка записи обработчика с фейковыми портами (сбой `put` даёт `503` и не делает вложение готовым)
|
||||
- [x] 2.1 Домен: `Filename`, `ImageKind`, `ImageInfo`, агрегат `Attachment` (`stage` → `pending`, `store` → `ready` с событием `AttachmentStored`), ошибки зоны
|
||||
- [x] 2.2 Порты: `ChatMembership`, `ObjectStorage` (`put`/`open`/`delete`, `ObjectContent`, `ObjectMissing`), `ImageInspector`, `AttachmentsUnitOfWork`, `AttachmentDirectory`
|
||||
- [x] 2.3 Команда `UploadAttachment` и обработчик: членство → имя → `Content-Type` → поток со счётчиком и SHA-256 → проверка изображения → `pending` → `put` → `ready`; запросы `GetAttachment`, `OpenAttachment`
|
||||
- [x] 2.4 Проверка группы: unit-тесты `Filename` (граничные и опасные имена), агрегата и порядка записи обработчика с фейковыми портами (сбой `put` даёт `503` и не делает вложение готовым)
|
||||
|
||||
## 3. Зона `attachments`: инфраструктура и HTTP
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
from messenger.shared.application.messagebus import CommandBus
|
||||
|
||||
|
||||
class AttachmentsCommandBus(CommandBus):
|
||||
__slots__ = ()
|
||||
@@ -0,0 +1,14 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.application.commands import Command
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UploadAttachment(Command):
|
||||
owner_id: UUID
|
||||
chat_id: UUID
|
||||
filename: str | None
|
||||
content_type: str | None
|
||||
body: AsyncIterator[bytes]
|
||||
@@ -0,0 +1,2 @@
|
||||
class ObjectMissingError(Exception):
|
||||
pass
|
||||
@@ -0,0 +1,77 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from hashlib import sha256
|
||||
|
||||
from messenger.attachments.application.commands import UploadAttachment
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentsUnitOfWork,
|
||||
ChatMembership,
|
||||
ImageInspector,
|
||||
ObjectStorage,
|
||||
)
|
||||
from messenger.attachments.domain.errors import ChatNotFound, PayloadTooLarge
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.attachments.domain.values import Filename, ImageKind
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
|
||||
|
||||
async def read_limited(body: AsyncIterator[bytes], limit: int) -> tuple[bytes, str]:
|
||||
chunks: list[bytes] = []
|
||||
digest = sha256()
|
||||
size = 0
|
||||
async for chunk in body:
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise PayloadTooLarge(f"тело больше {limit} байт")
|
||||
digest.update(chunk)
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks), digest.hexdigest()
|
||||
|
||||
|
||||
class UploadAttachmentHandler:
|
||||
__slots__ = ("_clock", "_ids", "_images", "_limit", "_membership", "_storage", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
membership: ChatMembership,
|
||||
images: ImageInspector,
|
||||
storage: ObjectStorage,
|
||||
*,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
limit: int,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._membership = membership
|
||||
self._images = images
|
||||
self._storage = storage
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
self._limit = limit
|
||||
|
||||
async def __call__(self, command: UploadAttachment) -> Attachment:
|
||||
if not await self._membership.is_member(command.chat_id, command.owner_id):
|
||||
raise ChatNotFound("чат не найден")
|
||||
filename = Filename(command.filename or "")
|
||||
declared = ImageKind.declared(command.content_type)
|
||||
data, digest = await read_limited(command.body, self._limit)
|
||||
image = await self._images.inspect(data, declared)
|
||||
attachment = Attachment.stage(
|
||||
attachment_id=self._ids.new_id(),
|
||||
chat_id=command.chat_id,
|
||||
owner_id=command.owner_id,
|
||||
filename=filename,
|
||||
image=image,
|
||||
size_bytes=len(data),
|
||||
sha256=digest,
|
||||
now=self._clock.now(),
|
||||
)
|
||||
async with self._uow.transaction():
|
||||
await self._uow.attachments.add(attachment)
|
||||
await self._uow.commit()
|
||||
await self._storage.put(attachment.object_key, data, attachment.content_type)
|
||||
attachment.store(self._clock.now())
|
||||
async with self._uow.transaction():
|
||||
await self._uow.attachments.save(attachment)
|
||||
await self._uow.commit()
|
||||
return attachment
|
||||
@@ -0,0 +1,51 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol, runtime_checkable
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
from messenger.shared.application.ports import UnitOfWork
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ObjectContent:
|
||||
size: int
|
||||
chunks: AsyncIterator[bytes]
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ObjectStorage(Protocol):
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None: ...
|
||||
|
||||
async def open(self, key: str) -> ObjectContent: ...
|
||||
|
||||
async def delete(self, key: str) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ImageInspector(Protocol):
|
||||
async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ChatMembership(Protocol):
|
||||
async def is_member(self, chat_id: UUID, user_id: UUID) -> bool: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentRepository(Protocol):
|
||||
async def add(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def save(self, attachment: Attachment) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentsUnitOfWork(UnitOfWork, Protocol):
|
||||
@property
|
||||
def attachments(self) -> AttachmentRepository: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentDirectory(Protocol):
|
||||
async def ready(self, attachment_id: UUID) -> Attachment | None: ...
|
||||
@@ -0,0 +1,46 @@
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.application.errors import ObjectMissingError
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentDirectory,
|
||||
ChatMembership,
|
||||
ObjectContent,
|
||||
ObjectStorage,
|
||||
)
|
||||
from messenger.attachments.domain.errors import AttachmentNotFound
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
|
||||
class GetAttachment:
|
||||
__slots__ = ("_attachments", "_membership")
|
||||
|
||||
def __init__(self, attachments: AttachmentDirectory, membership: ChatMembership) -> None:
|
||||
self._attachments = attachments
|
||||
self._membership = membership
|
||||
|
||||
async def __call__(self, attachment_id: UUID, user_id: UUID) -> Attachment:
|
||||
attachment = await self._attachments.ready(attachment_id)
|
||||
if attachment is None or not await self._membership.is_member(attachment.chat_id, user_id):
|
||||
raise AttachmentNotFound("вложение не найдено")
|
||||
return attachment
|
||||
|
||||
|
||||
class OpenAttachment:
|
||||
__slots__ = ("_get", "_logger", "_storage")
|
||||
|
||||
def __init__(self, get: GetAttachment, storage: ObjectStorage, logger: Logger) -> None:
|
||||
self._get = get
|
||||
self._storage = storage
|
||||
self._logger = logger
|
||||
|
||||
async def __call__(
|
||||
self, attachment_id: UUID, user_id: UUID
|
||||
) -> tuple[Attachment, ObjectContent]:
|
||||
attachment = await self._get(attachment_id, user_id)
|
||||
try:
|
||||
content = await self._storage.open(attachment.object_key)
|
||||
except ObjectMissingError as error:
|
||||
self._logger.warning("attachment.object_missing", attachment_id=str(attachment.id))
|
||||
raise AttachmentNotFound("вложение не найдено") from error
|
||||
return attachment, content
|
||||
@@ -0,0 +1,25 @@
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
|
||||
class AttachmentError(DomainError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidFilename(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UnsupportedImage(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class PayloadTooLarge(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class ChatNotFound(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotFound(AttachmentError):
|
||||
pass
|
||||
@@ -0,0 +1,13 @@
|
||||
from dataclasses import dataclass, field
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentStored(DomainEvent):
|
||||
attachment_id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
size_bytes: int
|
||||
name: str = field(init=False, default="attachment.stored")
|
||||
@@ -0,0 +1,78 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.events import AttachmentStored
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
OBJECT_PREFIX = "attachments/"
|
||||
|
||||
|
||||
class AttachmentStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
READY = "ready"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Attachment:
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: Filename
|
||||
image: ImageInfo
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
object_key: str
|
||||
status: AttachmentStatus
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
_events: list[DomainEvent] = field(init=False, default_factory=list, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
def stage(
|
||||
cls,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: Filename,
|
||||
image: ImageInfo,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
now: datetime,
|
||||
) -> Attachment:
|
||||
return cls(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
image=image,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256,
|
||||
object_key=f"{OBJECT_PREFIX}{attachment_id}",
|
||||
status=AttachmentStatus.PENDING,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
return self.image.kind.value
|
||||
|
||||
def store(self, now: datetime) -> None:
|
||||
self.status = AttachmentStatus.READY
|
||||
self.updated_at = max(now, self.created_at)
|
||||
self._events.append(
|
||||
AttachmentStored(
|
||||
attachment_id=self.id,
|
||||
chat_id=self.chat_id,
|
||||
owner_id=self.owner_id,
|
||||
size_bytes=self.size_bytes,
|
||||
)
|
||||
)
|
||||
|
||||
def collect_events(self) -> list[DomainEvent]:
|
||||
events, self._events = self._events, []
|
||||
return events
|
||||
@@ -0,0 +1,46 @@
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
|
||||
from messenger.attachments.domain.errors import InvalidFilename, UnsupportedImage
|
||||
|
||||
FILENAME_MAX = 255
|
||||
SEPARATORS = frozenset("/\\")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Filename:
|
||||
value: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.value.strip():
|
||||
raise InvalidFilename("параметр filename обязателен и не может быть пустым")
|
||||
if len(self.value) > FILENAME_MAX:
|
||||
raise InvalidFilename(f"параметр filename длиннее {FILENAME_MAX} символов Unicode")
|
||||
if any(c in SEPARATORS or unicodedata.category(c) == "Cc" for c in self.value):
|
||||
raise InvalidFilename(
|
||||
"параметр filename содержит разделитель пути или управляющий символ"
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
class ImageKind(StrEnum):
|
||||
PNG = "image/png"
|
||||
JPEG = "image/jpeg"
|
||||
|
||||
@classmethod
|
||||
def declared(cls, content_type: str | None) -> ImageKind:
|
||||
media = (content_type or "").partition(";")[0].strip().lower()
|
||||
try:
|
||||
return cls(media)
|
||||
except ValueError as error:
|
||||
raise UnsupportedImage("Content-Type должен быть image/png или image/jpeg") from error
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ImageInfo:
|
||||
kind: ImageKind
|
||||
width: int
|
||||
height: int
|
||||
@@ -0,0 +1,69 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.attachments.domain.errors import InvalidFilename, UnsupportedImage
|
||||
from messenger.attachments.domain.events import AttachmentStored
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
|
||||
|
||||
MOMENT = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw",
|
||||
[
|
||||
*("", " ", "\t\n", "../a.png", "a/b.png", "a\\b.png"),
|
||||
*("a\x00.png", "a\x01.png", "a\x7f.png", "a\n.png", "\x9f.png", "x" * 256),
|
||||
],
|
||||
)
|
||||
def test_filename_rejects_dangerous_and_empty(raw: str) -> None:
|
||||
with pytest.raises(InvalidFilename):
|
||||
Filename(raw)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["sample.png", "фото 1.png", "я" * 255, "👋.jpg", "a..b.png"])
|
||||
def test_filename_keeps_display_names(raw: str) -> None:
|
||||
assert Filename(raw).value == raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("header", "kind"),
|
||||
[
|
||||
("image/png", ImageKind.PNG),
|
||||
("IMAGE/JPEG", ImageKind.JPEG),
|
||||
("image/png; charset=binary", ImageKind.PNG),
|
||||
],
|
||||
)
|
||||
def test_declared_type_ignores_case_and_parameters(header: str, kind: ImageKind) -> None:
|
||||
assert ImageKind.declared(header) is kind
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header", [None, "", "image/gif", "application/octet-stream", "image/*"])
|
||||
def test_declared_type_accepts_only_png_and_jpeg(header: str | None) -> None:
|
||||
with pytest.raises(UnsupportedImage):
|
||||
ImageKind.declared(header)
|
||||
|
||||
|
||||
def test_attachment_is_pending_until_stored() -> None:
|
||||
attachment_id = uuid4()
|
||||
attachment = Attachment.stage(
|
||||
attachment_id=attachment_id,
|
||||
chat_id=uuid4(),
|
||||
owner_id=uuid4(),
|
||||
filename=Filename("a.png"),
|
||||
image=ImageInfo(ImageKind.PNG, 2, 3),
|
||||
size_bytes=10,
|
||||
sha256="0" * 64,
|
||||
now=MOMENT,
|
||||
)
|
||||
assert attachment.status is AttachmentStatus.PENDING
|
||||
assert attachment.object_key == f"attachments/{attachment_id}"
|
||||
assert attachment.collect_events() == []
|
||||
attachment.store(MOMENT - timedelta(seconds=1))
|
||||
assert attachment.status is AttachmentStatus.READY
|
||||
assert attachment.updated_at == MOMENT
|
||||
events = attachment.collect_events()
|
||||
assert [type(event) for event in events] == [AttachmentStored]
|
||||
assert attachment.collect_events() == []
|
||||
Reference in New Issue
Block a user