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
|
||||
@@ -0,0 +1,24 @@
|
||||
from pydantic import Field, SecretStr
|
||||
|
||||
from messenger.shared.config import Settings
|
||||
|
||||
UPLOAD_BYTES_MAX = 10_485_760
|
||||
IMAGE_PIXELS_MAX = 40_000_000
|
||||
|
||||
|
||||
class AttachmentsSettings(Settings):
|
||||
s3_endpoint: str = "http://s3:9000"
|
||||
s3_region: str = "us-east-1"
|
||||
s3_bucket: str = Field(default="messenger-attachments", min_length=3)
|
||||
s3_access_key_id: SecretStr = Field(min_length=3)
|
||||
s3_secret_access_key: SecretStr = Field(min_length=8)
|
||||
s3_connect_timeout_seconds: float = Field(default=1.0, gt=0, le=30)
|
||||
s3_read_timeout_seconds: float = Field(default=2.0, gt=0, le=60)
|
||||
s3_max_attempts: int = Field(default=2, ge=1, le=5)
|
||||
max_upload_bytes: int = Field(default=UPLOAD_BYTES_MAX, ge=1, le=UPLOAD_BYTES_MAX)
|
||||
max_image_pixels: int = Field(default=IMAGE_PIXELS_MAX, ge=1, le=IMAGE_PIXELS_MAX)
|
||||
image_check_concurrency: int = Field(default=2, ge=1, le=16)
|
||||
upload_concurrency: int = Field(default=3, ge=1, le=64)
|
||||
upload_grace_seconds: int = Field(default=900, ge=60)
|
||||
upload_sweep_interval_seconds: float = Field(default=30.0, gt=0)
|
||||
upload_sweep_batch: int = Field(default=100, ge=1, le=10_000)
|
||||
@@ -0,0 +1,29 @@
|
||||
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
|
||||
|
||||
|
||||
class UploadAborted(AttachmentError):
|
||||
pass
|
||||
@@ -0,0 +1,21 @@
|
||||
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")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentDiscarded(DomainEvent):
|
||||
attachment_id: UUID
|
||||
chat_id: UUID
|
||||
reason: str
|
||||
name: str = field(init=False, default="attachment.discarded")
|
||||
@@ -0,0 +1,83 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded, 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 discard(self, reason: str) -> None:
|
||||
self._events.append(
|
||||
AttachmentDiscarded(attachment_id=self.id, chat_id=self.chat_id, reason=reason)
|
||||
)
|
||||
|
||||
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,18 @@
|
||||
from messenger.attachments.domain.errors import (
|
||||
AttachmentNotFound,
|
||||
ChatNotFound,
|
||||
InvalidFilename,
|
||||
PayloadTooLarge,
|
||||
UnsupportedImage,
|
||||
UploadAborted,
|
||||
)
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidFilename: ("invalid_request", 400),
|
||||
UploadAborted: ("invalid_request", 400),
|
||||
ChatNotFound: ("not_found", 404),
|
||||
AttachmentNotFound: ("not_found", 404),
|
||||
PayloadTooLarge: ("payload_too_large", 413),
|
||||
UnsupportedImage: ("unsupported_media_type", 415),
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from dishka.integrations.fastapi import FromDishka, inject
|
||||
from fastapi import APIRouter, Query, Request, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import UploadAttachment
|
||||
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
|
||||
from messenger.attachments.domain.errors import UploadAborted
|
||||
from messenger.attachments.entrypoints.schemas import AttachmentOut
|
||||
from messenger.shared.entrypoints.actor import Actor
|
||||
|
||||
UPLOAD_PATH = re.compile(r"/api/v1/chats/[^/]+/attachments/?")
|
||||
CONTENT_HEADERS = {"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"}
|
||||
|
||||
uploads_router = APIRouter(prefix="/api/v1/chats/{chat_id}/attachments", tags=["attachments"])
|
||||
attachments_router = APIRouter(prefix="/api/v1/attachments", tags=["attachments"])
|
||||
|
||||
|
||||
async def body_of(request: Request) -> AsyncIterator[bytes]:
|
||||
try:
|
||||
async for chunk in request.stream():
|
||||
yield chunk
|
||||
except ClientDisconnect as error:
|
||||
raise UploadAborted("клиент оборвал загрузку до конца тела") from error
|
||||
|
||||
|
||||
@uploads_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
@inject
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
actor: Actor,
|
||||
request: Request,
|
||||
bus: FromDishka[AttachmentsCommandBus],
|
||||
filename: Annotated[str | None, Query()] = None,
|
||||
) -> AttachmentOut:
|
||||
attachment = await bus.execute(
|
||||
UploadAttachment(
|
||||
owner_id=actor,
|
||||
chat_id=chat_id,
|
||||
filename=filename,
|
||||
content_type=request.headers.get("content-type"),
|
||||
body=body_of(request),
|
||||
)
|
||||
)
|
||||
return AttachmentOut.of(attachment)
|
||||
|
||||
|
||||
@attachments_router.get("/{attachment_id}")
|
||||
@inject
|
||||
async def read_attachment(
|
||||
attachment_id: UUID,
|
||||
actor: Actor,
|
||||
query: FromDishka[GetAttachment],
|
||||
) -> AttachmentOut:
|
||||
return AttachmentOut.of(await query(attachment_id, actor))
|
||||
|
||||
|
||||
@attachments_router.get("/{attachment_id}/content")
|
||||
@inject
|
||||
async def download_attachment(
|
||||
attachment_id: UUID,
|
||||
actor: Actor,
|
||||
query: FromDishka[OpenAttachment],
|
||||
_variant: Annotated[Literal["original"], Query(alias="variant")] = "original",
|
||||
) -> StreamingResponse:
|
||||
attachment, content = await query(attachment_id, actor)
|
||||
return StreamingResponse(
|
||||
content.chunks,
|
||||
media_type=attachment.content_type,
|
||||
headers={**CONTENT_HEADERS, "Content-Length": str(content.size)},
|
||||
)
|
||||
@@ -0,0 +1,112 @@
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from dishka import Provider, Scope, provide
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import SweepAbandonedUploads, UploadAttachment
|
||||
from messenger.attachments.application.handlers import (
|
||||
SweepAbandonedUploadsHandler,
|
||||
UploadAttachmentHandler,
|
||||
UploadSlots,
|
||||
)
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentDirectory,
|
||||
AttachmentsUnitOfWork,
|
||||
ChatMembership,
|
||||
ImageInspector,
|
||||
ObjectStorage,
|
||||
)
|
||||
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.attachments.infrastructure.images import PillowImageInspector
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
PostgresAttachmentDirectory,
|
||||
PostgresAttachmentsUnitOfWork,
|
||||
)
|
||||
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.messagebus import CommandHandler
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
class AttachmentsProvider(Provider):
|
||||
def __init__(self, settings: AttachmentsSettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> AttachmentsSettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
async def storage(self, settings: AttachmentsSettings) -> AsyncIterator[ObjectStorage]:
|
||||
async with s3_client(
|
||||
endpoint=settings.s3_endpoint,
|
||||
region=settings.s3_region,
|
||||
access_key_id=settings.s3_access_key_id.get_secret_value(),
|
||||
secret_access_key=settings.s3_secret_access_key.get_secret_value(),
|
||||
connect_timeout=settings.s3_connect_timeout_seconds,
|
||||
read_timeout=settings.s3_read_timeout_seconds,
|
||||
max_attempts=settings.s3_max_attempts,
|
||||
) as client:
|
||||
yield S3ObjectStorage(client, settings.s3_bucket)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def images(self, settings: AttachmentsSettings) -> ImageInspector:
|
||||
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def slots(self, settings: AttachmentsSettings) -> UploadSlots:
|
||||
return UploadSlots(settings.upload_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def directory(self, database: Database) -> AttachmentDirectory:
|
||||
return PostgresAttachmentDirectory(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def attachment(
|
||||
self, directory: AttachmentDirectory, membership: ChatMembership
|
||||
) -> GetAttachment:
|
||||
return GetAttachment(directory, membership)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def content(
|
||||
self, attachment: GetAttachment, storage: ObjectStorage, logger: Logger
|
||||
) -> OpenAttachment:
|
||||
return OpenAttachment(attachment, storage, logger)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
membership: ChatMembership,
|
||||
images: ImageInspector,
|
||||
storage: ObjectStorage,
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
settings: AttachmentsSettings,
|
||||
slots: UploadSlots,
|
||||
logger: Logger,
|
||||
) -> AttachmentsCommandBus:
|
||||
upload = UploadAttachmentHandler(
|
||||
uow,
|
||||
membership,
|
||||
images,
|
||||
storage,
|
||||
clock=clock,
|
||||
ids=ids,
|
||||
limit=settings.max_upload_bytes,
|
||||
slots=slots,
|
||||
logger=logger,
|
||||
)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
UploadAttachment: upload,
|
||||
SweepAbandonedUploads: SweepAbandonedUploadsHandler(uow, storage, clock),
|
||||
}
|
||||
return AttachmentsCommandBus(handlers, uow, publisher)
|
||||
@@ -0,0 +1,28 @@
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentStored
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
LOG_FIELDS = frozenset({"attachment_id", "chat_id", "actor_id", "size_bytes", "count"})
|
||||
|
||||
|
||||
class AttachmentsJournal:
|
||||
__slots__ = ("_logger",)
|
||||
|
||||
def __init__(self, logger: Logger) -> None:
|
||||
self._logger = logger
|
||||
|
||||
async def on_attachment_stored(self, event: AttachmentStored) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_stored",
|
||||
attachment_id=str(event.attachment_id),
|
||||
chat_id=str(event.chat_id),
|
||||
actor_id=str(event.owner_id),
|
||||
size_bytes=event.size_bytes,
|
||||
)
|
||||
|
||||
async def on_attachment_discarded(self, event: AttachmentDiscarded) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_discarded",
|
||||
attachment_id=str(event.attachment_id),
|
||||
chat_id=str(event.chat_id),
|
||||
reason=event.reason,
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
|
||||
|
||||
class AttachmentOut(BaseModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: Literal["ready"] = "ready"
|
||||
variants: tuple[()] = ()
|
||||
error_code: None = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@classmethod
|
||||
def of(cls, attachment: Attachment) -> AttachmentOut:
|
||||
return cls(
|
||||
id=attachment.id,
|
||||
chat_id=attachment.chat_id,
|
||||
owner_id=attachment.owner_id,
|
||||
filename=attachment.filename.value,
|
||||
content_type=attachment.content_type,
|
||||
size_bytes=attachment.size_bytes,
|
||||
sha256=attachment.sha256,
|
||||
created_at=attachment.created_at,
|
||||
updated_at=attachment.updated_at,
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import AsyncContainer
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import SweepAbandonedUploads
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
|
||||
class UploadSweeper:
|
||||
__slots__ = ("_command", "_container", "_interval", "_logger", "_task")
|
||||
|
||||
def __init__(
|
||||
self, container: AsyncContainer, settings: AttachmentsSettings, logger: Logger
|
||||
) -> None:
|
||||
self._container = container
|
||||
self._logger = logger
|
||||
self._interval = settings.upload_sweep_interval_seconds
|
||||
self._command = SweepAbandonedUploads(
|
||||
grace=timedelta(seconds=settings.upload_grace_seconds),
|
||||
limit=settings.upload_sweep_batch,
|
||||
)
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
self._task = asyncio.create_task(self._run())
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._task is None:
|
||||
return
|
||||
self._task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._task
|
||||
self._task = None
|
||||
|
||||
async def sweep(self) -> int:
|
||||
async with self._container() as scope:
|
||||
bus = await scope.get(AttachmentsCommandBus)
|
||||
return await bus.execute(self._command)
|
||||
|
||||
async def _run(self) -> None:
|
||||
while True:
|
||||
await asyncio.sleep(self._interval)
|
||||
try:
|
||||
swept = await self.sweep()
|
||||
except Exception as error:
|
||||
self._logger.warning("attachments.sweep_failed", error=type(error).__name__)
|
||||
continue
|
||||
if swept:
|
||||
self._logger.info("attachments.swept", count=swept)
|
||||
@@ -0,0 +1,49 @@
|
||||
import asyncio
|
||||
import warnings
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from messenger.attachments.domain.errors import PayloadTooLarge, UnsupportedImage
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
|
||||
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
|
||||
BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning)
|
||||
JPEG_SCALE = 8
|
||||
|
||||
|
||||
class PillowImageInspector:
|
||||
__slots__ = ("_max_pixels", "_slots")
|
||||
|
||||
def __init__(self, max_pixels: int, concurrency: int) -> None:
|
||||
self._max_pixels = max_pixels
|
||||
self._slots = asyncio.Semaphore(concurrency)
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
|
||||
async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
|
||||
async with self._slots:
|
||||
return await asyncio.to_thread(self._inspect, data, declared)
|
||||
|
||||
def _inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
|
||||
try:
|
||||
image = Image.open(BytesIO(data), formats=tuple(KINDS))
|
||||
except BOMBS as error:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей") from error
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("содержимое не является изображением PNG или JPEG") from error
|
||||
with image:
|
||||
kind = KINDS[str(image.format)]
|
||||
width, height = image.size
|
||||
if kind is not declared:
|
||||
raise UnsupportedImage("содержимое не совпадает с заявленным Content-Type")
|
||||
if width * height > self._max_pixels:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей")
|
||||
try:
|
||||
if kind is ImageKind.JPEG:
|
||||
image.draft("RGB", (width // JPEG_SCALE or 1, height // JPEG_SCALE or 1))
|
||||
image.load()
|
||||
else:
|
||||
image.verify()
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("изображение повреждено или обрезано") from error
|
||||
return ImageInfo(kind, width, height)
|
||||
@@ -0,0 +1,121 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.attachments.domain.errors import ChatNotFound
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.postgres import (
|
||||
Connection,
|
||||
Database,
|
||||
EventSource,
|
||||
PostgresUnitOfWork,
|
||||
)
|
||||
|
||||
INSERT = """
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, object_key, status, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
|
||||
"""
|
||||
MARK = "UPDATE attachments SET status = $2, updated_at = $3 WHERE id = $1 AND status = 'pending'"
|
||||
COLUMNS = """
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height,
|
||||
object_key, status, created_at, updated_at
|
||||
FROM attachments
|
||||
"""
|
||||
READY = COLUMNS + "WHERE id = $1 AND status = 'ready'"
|
||||
LOCK = COLUMNS + "WHERE id = $1 FOR UPDATE"
|
||||
ABANDONED = (
|
||||
COLUMNS
|
||||
+ """WHERE status = 'pending' AND created_at < $1
|
||||
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
|
||||
)
|
||||
REMOVE = "DELETE FROM attachments WHERE id = $1 AND status = 'pending'"
|
||||
|
||||
|
||||
def attachment_of(row: Record) -> Attachment:
|
||||
return Attachment(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
owner_id=row["owner_id"],
|
||||
filename=Filename(row["filename"]),
|
||||
image=ImageInfo(ImageKind(row["content_type"]), row["width"], row["height"]),
|
||||
size_bytes=row["size_bytes"],
|
||||
sha256=row["sha256"],
|
||||
object_key=row["object_key"],
|
||||
status=AttachmentStatus(row["status"]),
|
||||
created_at=row["created_at"],
|
||||
updated_at=row["updated_at"],
|
||||
)
|
||||
|
||||
|
||||
class PostgresAttachmentRepository:
|
||||
__slots__ = ("_connection", "_seen")
|
||||
|
||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
||||
self._connection = connection
|
||||
self._seen = seen
|
||||
|
||||
async def add(self, attachment: Attachment) -> None:
|
||||
try:
|
||||
await self._connection.execute(
|
||||
INSERT,
|
||||
attachment.id,
|
||||
attachment.chat_id,
|
||||
attachment.owner_id,
|
||||
attachment.filename.value,
|
||||
attachment.content_type,
|
||||
attachment.size_bytes,
|
||||
attachment.sha256,
|
||||
attachment.image.width,
|
||||
attachment.image.height,
|
||||
attachment.object_key,
|
||||
attachment.status.value,
|
||||
attachment.created_at,
|
||||
attachment.updated_at,
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
raise ChatNotFound("чат не найден") from error
|
||||
self._seen.append(attachment)
|
||||
|
||||
async def save(self, attachment: Attachment) -> None:
|
||||
done = await self._connection.execute(
|
||||
MARK, attachment.id, attachment.status.value, attachment.updated_at
|
||||
)
|
||||
if done == "UPDATE 0":
|
||||
raise Unavailable("намерение загрузки уже снято уборкой")
|
||||
self._seen.append(attachment)
|
||||
|
||||
async def lock(self, attachment_id: UUID) -> Attachment | None:
|
||||
row = await self._connection.fetchrow(LOCK, attachment_id)
|
||||
return None if row is None else attachment_of(row)
|
||||
|
||||
async def next_abandoned(self, before: datetime) -> Attachment | None:
|
||||
row = await self._connection.fetchrow(ABANDONED, before)
|
||||
return None if row is None else attachment_of(row)
|
||||
|
||||
async def remove(self, attachment: Attachment) -> None:
|
||||
await self._connection.execute(REMOVE, attachment.id)
|
||||
self._seen.append(attachment)
|
||||
|
||||
|
||||
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def attachments(self) -> PostgresAttachmentRepository:
|
||||
return PostgresAttachmentRepository(self.connection, self.seen)
|
||||
|
||||
|
||||
class PostgresAttachmentDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
self._database = database
|
||||
|
||||
async def ready(self, attachment_id: UUID) -> Attachment | None:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(READY, attachment_id)
|
||||
return None if row is None else attachment_of(row)
|
||||
@@ -0,0 +1,89 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
from aiobotocore.session import get_session
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from botocore.handlers import add_expect_header
|
||||
|
||||
from messenger.attachments.application.errors import ObjectMissingError
|
||||
from messenger.attachments.application.ports import ObjectContent
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
CHUNK_BYTES = 64 * 1024
|
||||
MISSING = frozenset({"NoSuchKey", "404", "NotFound"})
|
||||
FAILURES = (BotoCoreError, ClientError, OSError, TimeoutError)
|
||||
|
||||
|
||||
def missing(error: Exception) -> bool:
|
||||
return isinstance(error, ClientError) and error.response.get("Error", {}).get("Code") in MISSING
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def s3_client(
|
||||
*,
|
||||
endpoint: str,
|
||||
region: str,
|
||||
access_key_id: str,
|
||||
secret_access_key: str,
|
||||
connect_timeout: float,
|
||||
read_timeout: float,
|
||||
max_attempts: int,
|
||||
) -> AsyncIterator[Any]:
|
||||
config = Config(
|
||||
region_name=region,
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=connect_timeout,
|
||||
read_timeout=read_timeout,
|
||||
retries={"mode": "standard", "max_attempts": max_attempts},
|
||||
max_pool_connections=32,
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
)
|
||||
async with get_session().create_client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
aws_access_key_id=access_key_id,
|
||||
aws_secret_access_key=secret_access_key,
|
||||
config=config,
|
||||
) as client:
|
||||
client.meta.events.unregister("before-call.s3", add_expect_header)
|
||||
yield client
|
||||
|
||||
|
||||
class S3ObjectStorage:
|
||||
__slots__ = ("_bucket", "_client")
|
||||
|
||||
def __init__(self, client: Any, bucket: str) -> None:
|
||||
self._client = client
|
||||
self._bucket = bucket
|
||||
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None:
|
||||
try:
|
||||
await self._client.put_object(
|
||||
Bucket=self._bucket, Key=key, Body=data, ContentType=content_type
|
||||
)
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def open(self, key: str) -> ObjectContent:
|
||||
try:
|
||||
response = await self._client.get_object(Bucket=self._bucket, Key=key)
|
||||
except FAILURES as error:
|
||||
if missing(error):
|
||||
raise ObjectMissingError(key) from error
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
return ObjectContent(size=response["ContentLength"], chunks=self._chunks(response["Body"]))
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
try:
|
||||
await self._client.delete_object(Bucket=self._bucket, Key=key)
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def _chunks(self, body: Any) -> AsyncIterator[bytes]:
|
||||
async with body as stream:
|
||||
async for chunk in stream.iter_chunks(CHUNK_BYTES):
|
||||
yield chunk
|
||||
Reference in New Issue
Block a user