Serve attachment upload, metadata and download through the API

Add the adapters behind the attachments ports: PostgreSQL for the
pending and ready rows, with a foreign key violation on the chat member
turned into 404; Pillow that opens only PNG and JPEG, refuses a type
that differs from Content-Type, checks the pixel count from the header
before any decoding, verifies PNG chunks and decodes JPEG at 1/8 scale
in a worker thread under a semaphore; and S3 on aiobotocore with path
style, SigV4, short timeouts and checksums only when required. botocore
sends Expect: 100-continue for streamed bodies and RustFS behind the
Docker port proxy never answers it, so the PUT hung until the read
timeout; the handler that adds the header is unregistered.

The HTTP layer streams the raw body into the use case, returns the
contract Attachment and streams the original back with its content
type and length and no redirect. The request pipeline takes a body
limit per route, so uploads may carry 10 MiB while JSON stays at 1 MiB.
main.py wires the zone and answers its membership port from the
messaging chat directory.

Tests run the API with an in-memory object store: download by another
member, 404 for strangers, the exact 10 MiB limit and one byte over it
with Content-Length and chunked, 40 MP and above, spoofed and truncated
images, unsupported types, dangerous names, the variant, a failing
store and a lost object.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-28 20:44:32 +03:00
co-authored by Claude Opus 5.5
parent 76c9673ab3
commit 00826a40d3
21 changed files with 1334 additions and 15 deletions
@@ -0,0 +1,98 @@
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.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'"
READY = """
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height,
object_key, status, created_at, updated_at
FROM attachments
WHERE id = $1 AND status = 'ready'
"""
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:
await self._connection.execute(
MARK, attachment.id, attachment.status.value, attachment.updated_at
)
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)