forked from mtusi2026/mtusi2026lab5
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:
co-authored by
Claude Opus 5.5
parent
1210dd899c
commit
540fcb35ba
@@ -0,0 +1,5 @@
|
||||
from messenger.shared.application.messagebus import CommandBus
|
||||
|
||||
|
||||
class AttachmentsCommandBus(CommandBus):
|
||||
__slots__ = ()
|
||||
@@ -0,0 +1,21 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
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]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SweepAbandonedUploads(Command):
|
||||
grace: timedelta
|
||||
limit: int
|
||||
@@ -0,0 +1,2 @@
|
||||
class ObjectMissingError(Exception):
|
||||
pass
|
||||
@@ -0,0 +1,150 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from hashlib import sha256
|
||||
|
||||
from messenger.attachments.application.commands import SweepAbandonedUploads, 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, AttachmentStatus
|
||||
from messenger.attachments.domain.values import Filename, ImageKind
|
||||
from messenger.shared.application.ports import Clock, IdGenerator, Logger
|
||||
|
||||
|
||||
class UploadSlots(asyncio.Semaphore):
|
||||
pass
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
async def drop(
|
||||
uow: AttachmentsUnitOfWork, storage: ObjectStorage, attachment: Attachment, reason: str
|
||||
) -> None:
|
||||
await storage.delete(attachment.object_key)
|
||||
attachment.discard(reason)
|
||||
await uow.attachments.remove(attachment)
|
||||
await uow.commit()
|
||||
|
||||
|
||||
class UploadAttachmentHandler:
|
||||
__slots__ = (
|
||||
"_clock",
|
||||
"_ids",
|
||||
"_images",
|
||||
"_limit",
|
||||
"_logger",
|
||||
"_membership",
|
||||
"_slots",
|
||||
"_storage",
|
||||
"_uow",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
membership: ChatMembership,
|
||||
images: ImageInspector,
|
||||
storage: ObjectStorage,
|
||||
*,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
limit: int,
|
||||
slots: UploadSlots,
|
||||
logger: Logger,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._membership = membership
|
||||
self._images = images
|
||||
self._storage = storage
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
self._limit = limit
|
||||
self._slots = slots
|
||||
self._logger = logger
|
||||
|
||||
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)
|
||||
async with self._slots:
|
||||
attachment = await self._write(command, filename, declared)
|
||||
attachment.store(self._clock.now())
|
||||
try:
|
||||
async with self._uow.transaction():
|
||||
await self._uow.attachments.save(attachment)
|
||||
await self._uow.commit()
|
||||
except Exception:
|
||||
await self._compensate(attachment)
|
||||
raise
|
||||
return attachment
|
||||
|
||||
async def _write(
|
||||
self, command: UploadAttachment, filename: Filename, declared: ImageKind
|
||||
) -> Attachment:
|
||||
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)
|
||||
return attachment
|
||||
|
||||
async def _compensate(self, staged: Attachment) -> None:
|
||||
try:
|
||||
async with self._uow.transaction():
|
||||
current = await self._uow.attachments.lock(staged.id)
|
||||
if current is None:
|
||||
await self._storage.delete(staged.object_key)
|
||||
elif current.status is AttachmentStatus.PENDING:
|
||||
await drop(self._uow, self._storage, current, "compensation")
|
||||
except Exception as error:
|
||||
self._logger.warning(
|
||||
"attachment.compensation_failed",
|
||||
attachment_id=str(staged.id),
|
||||
error=type(error).__name__,
|
||||
)
|
||||
|
||||
|
||||
class SweepAbandonedUploadsHandler:
|
||||
__slots__ = ("_clock", "_storage", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, storage: ObjectStorage, clock: Clock) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
self._clock = clock
|
||||
|
||||
async def __call__(self, command: SweepAbandonedUploads) -> int:
|
||||
before = self._clock.now() - command.grace
|
||||
for swept in range(command.limit):
|
||||
async with self._uow.transaction():
|
||||
abandoned = await self._uow.attachments.next_abandoned(before)
|
||||
if abandoned is None:
|
||||
return swept
|
||||
await drop(self._uow, self._storage, abandoned, "abandoned")
|
||||
return command.limit
|
||||
@@ -0,0 +1,58 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
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: ...
|
||||
|
||||
async def lock(self, attachment_id: UUID) -> Attachment | None: ...
|
||||
|
||||
async def next_abandoned(self, before: datetime) -> Attachment | None: ...
|
||||
|
||||
async def remove(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
|
||||
Reference in New Issue
Block a user