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>
90 lines
3.1 KiB
Python
90 lines
3.1 KiB
Python
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
|