fix s3 storage
This commit is contained in:
+121
-46
@@ -23,12 +23,17 @@ from app.errors.exceptions import (
|
||||
unavailable,
|
||||
unsupported_media_type,
|
||||
)
|
||||
from app.errors.handlers import RECOVERABLE_STORAGE_ERRORS, log_recoverable_error, operation_timeout
|
||||
from app.errors.handlers import (
|
||||
RECOVERABLE_STORAGE_ERRORS,
|
||||
log_recoverable_error,
|
||||
operation_timeout,
|
||||
)
|
||||
from app.schemas.attachment import Attachment
|
||||
from app.schemas.user import User
|
||||
from app.storage import attachments as repository
|
||||
from app.storage.s3 import MinioStorage
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CleanupResult:
|
||||
examined: int
|
||||
@@ -45,14 +50,14 @@ class OriginalFile:
|
||||
|
||||
def require_storage(storage: MinioStorage | None) -> MinioStorage:
|
||||
if storage is None:
|
||||
raise unavailable('Объектное хранилище не настроено')
|
||||
raise unavailable("Объектное хранилище не настроено")
|
||||
return storage
|
||||
|
||||
|
||||
def validate_declared_size(value: str | None, maximum: int) -> None:
|
||||
if value is not None:
|
||||
if not value.isascii() or not value.isdecimal() or len(value) > 20:
|
||||
raise invalid_request('Некорректный Content-Length')
|
||||
raise invalid_request("Некорректный Content-Length")
|
||||
if int(value) > maximum:
|
||||
raise payload_too_large()
|
||||
|
||||
@@ -68,28 +73,45 @@ def upload_slot(capacity: RequestCapacity) -> Iterator[None]:
|
||||
|
||||
|
||||
async def receive_attachment(
|
||||
session: AsyncSession, storage: MinioStorage | None, user: User, chat_id: UUID,
|
||||
*, capacity: RequestCapacity, filename: str, content_type: str,
|
||||
declared_length: str | None, chunks: AsyncIterator[bytes],
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage | None,
|
||||
user: User,
|
||||
chat_id: UUID,
|
||||
*,
|
||||
capacity: RequestCapacity,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
declared_length: str | None,
|
||||
chunks: AsyncIterator[bytes],
|
||||
) -> Attachment:
|
||||
storage = require_storage(storage)
|
||||
validate_declared_size(declared_length, storage.settings.max_upload_bytes)
|
||||
timeout_error = invalid_request('Истекло время загрузки')
|
||||
timeout_error = invalid_request("Истекло время загрузки")
|
||||
with upload_slot(capacity):
|
||||
async with operation_timeout(storage.settings.upload_timeout_seconds, timeout_error):
|
||||
async with operation_timeout(
|
||||
storage.settings.upload_timeout_seconds, timeout_error
|
||||
):
|
||||
result = await upload_attachment(
|
||||
session, storage, user, chat_id, filename=filename,
|
||||
content_type=content_type, chunks=chunks,
|
||||
session,
|
||||
storage,
|
||||
user,
|
||||
chat_id,
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
chunks=chunks,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
async def read_original(
|
||||
chunks: AsyncIterator[bytes], path: Path, maximum: int, chunk_bytes: int,
|
||||
chunks: AsyncIterator[bytes],
|
||||
path: Path,
|
||||
maximum: int,
|
||||
chunk_bytes: int,
|
||||
) -> OriginalFile:
|
||||
checksum = hashlib.sha256()
|
||||
size = 0
|
||||
with path.open('wb') as target:
|
||||
with path.open("wb") as target:
|
||||
async for chunk in chunks:
|
||||
size += len(chunk)
|
||||
if size > maximum:
|
||||
@@ -97,13 +119,15 @@ async def read_original(
|
||||
checksum.update(chunk)
|
||||
view = memoryview(chunk)
|
||||
for offset in range(0, len(view), chunk_bytes):
|
||||
target.write(view[offset:offset + chunk_bytes])
|
||||
target.write(view[offset : offset + chunk_bytes])
|
||||
if size == 0:
|
||||
raise unsupported_media_type('Пустой файл')
|
||||
raise unsupported_media_type("Пустой файл")
|
||||
return OriginalFile(path, size, checksum.hexdigest())
|
||||
|
||||
|
||||
async def compensate_upload(session: AsyncSession, storage: MinioStorage, id: UUID) -> None:
|
||||
async def compensate_upload(
|
||||
session: AsyncSession, storage: MinioStorage, id: UUID
|
||||
) -> None:
|
||||
"""Неоднозначный COMMIT сначала проверяется в БД: готовый объект не удаляется."""
|
||||
await session.rollback()
|
||||
intent = await repository.lock_upload(session, id)
|
||||
@@ -114,37 +138,54 @@ async def compensate_upload(session: AsyncSession, storage: MinioStorage, id: UU
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def recover_upload(session: AsyncSession, storage: MinioStorage, id: UUID) -> None:
|
||||
async def recover_upload(
|
||||
session: AsyncSession, storage: MinioStorage, id: UUID
|
||||
) -> None:
|
||||
"""Локальное восстановление после ошибки; журнал остаётся при отказе компенсации."""
|
||||
try:
|
||||
await compensate_upload(session, storage, id)
|
||||
except RECOVERABLE_STORAGE_ERRORS as error:
|
||||
log_recoverable_error('Upload compensation', error)
|
||||
log_recoverable_error("Upload compensation", error)
|
||||
# Ошибка повторного rollback не должна скрыть исходную ошибку или отмену.
|
||||
with suppress(*RECOVERABLE_STORAGE_ERRORS):
|
||||
await session.rollback()
|
||||
|
||||
|
||||
async def publish_original(
|
||||
session: AsyncSession, storage: MinioStorage, user: User, chat_id: UUID,
|
||||
*, original: OriginalFile, filename: str, content_type: str,
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage,
|
||||
user: User,
|
||||
chat_id: UUID,
|
||||
*,
|
||||
original: OriginalFile,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
) -> Attachment:
|
||||
id = uuid4()
|
||||
key = f'originals/{uuid4().hex}'
|
||||
key = f"originals/{uuid4().hex}"
|
||||
# Журнал устойчив до PUT, включая аварию процесса и неоднозначный COMMIT.
|
||||
await repository.reserve_upload(session, id, key)
|
||||
await session.commit()
|
||||
try:
|
||||
if await repository.lock_upload(session, id) is None:
|
||||
raise unavailable('Загрузка отменена до записи оригинала')
|
||||
raise unavailable("Загрузка отменена до записи оригинала")
|
||||
await storage.put_file(
|
||||
key, original.path, size_bytes=original.size_bytes,
|
||||
content_type=content_type, sha256=original.sha256,
|
||||
key,
|
||||
original.path,
|
||||
size_bytes=original.size_bytes,
|
||||
content_type=content_type,
|
||||
sha256=original.sha256,
|
||||
)
|
||||
record = await repository.create_attachment(
|
||||
session, id=id, chat_id=chat_id, owner_id=user.id, object_key=key,
|
||||
filename=filename, content_type=content_type,
|
||||
size_bytes=original.size_bytes, sha256=original.sha256,
|
||||
session,
|
||||
id=id,
|
||||
chat_id=chat_id,
|
||||
owner_id=user.id,
|
||||
object_key=key,
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
size_bytes=original.size_bytes,
|
||||
sha256=original.sha256,
|
||||
)
|
||||
await repository.finish_upload(session, id)
|
||||
result = Attachment.model_validate(record)
|
||||
@@ -158,29 +199,45 @@ async def publish_original(
|
||||
|
||||
|
||||
async def upload_attachment(
|
||||
session: AsyncSession, storage: MinioStorage, user: User, chat_id: UUID,
|
||||
*, filename: str, content_type: str, chunks: AsyncIterator[bytes],
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage,
|
||||
user: User,
|
||||
chat_id: UUID,
|
||||
*,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
chunks: AsyncIterator[bytes],
|
||||
) -> Attachment:
|
||||
await ensure_chat_member(session, user, chat_id)
|
||||
validate_filename(filename)
|
||||
if content_type not in {'image/png', 'image/jpeg'}:
|
||||
raise unsupported_media_type('Принимаются только image/png и image/jpeg')
|
||||
if content_type not in {"image/png", "image/jpeg"}:
|
||||
raise unsupported_media_type("Принимаются только image/png и image/jpeg")
|
||||
# Не держим соединение PostgreSQL во время чтения медленного клиента.
|
||||
await session.rollback()
|
||||
settings = storage.settings
|
||||
with TemporaryDirectory(prefix='messenger-upload-') as directory:
|
||||
with TemporaryDirectory(prefix="messenger-upload-") as directory:
|
||||
original = await read_original(
|
||||
chunks, Path(directory) / 'original', settings.max_upload_bytes, settings.chunk_bytes,
|
||||
chunks,
|
||||
Path(directory) / "original",
|
||||
settings.max_upload_bytes,
|
||||
settings.chunk_bytes,
|
||||
)
|
||||
await validate_image(original.path, content_type, settings)
|
||||
result = await publish_original(
|
||||
session, storage, user, chat_id, original=original,
|
||||
filename=filename, content_type=content_type,
|
||||
session,
|
||||
storage,
|
||||
user,
|
||||
chat_id,
|
||||
original=original,
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
async def get_attachment(session: AsyncSession, user: User, attachment_id: UUID) -> Attachment:
|
||||
async def get_attachment(
|
||||
session: AsyncSession, user: User, attachment_id: UUID
|
||||
) -> Attachment:
|
||||
record = await repository.get_attachment(session, attachment_id)
|
||||
if record is None:
|
||||
raise not_found()
|
||||
@@ -189,41 +246,59 @@ async def get_attachment(session: AsyncSession, user: User, attachment_id: UUID)
|
||||
|
||||
|
||||
async def download_attachment(
|
||||
session: AsyncSession, storage: MinioStorage | None, user: User, attachment_id: UUID,
|
||||
*, variant: str = 'original',
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage | None,
|
||||
user: User,
|
||||
attachment_id: UUID,
|
||||
*,
|
||||
variant: str = "original",
|
||||
) -> tuple[Attachment, AsyncIterator[bytes]]:
|
||||
result = await get_attachment(session, user, attachment_id)
|
||||
if variant != 'original':
|
||||
if variant != "original":
|
||||
raise not_found()
|
||||
storage = require_storage(storage)
|
||||
record = await repository.get_attachment(session, attachment_id)
|
||||
if record is None:
|
||||
raise not_found()
|
||||
key = record.object_key
|
||||
await session.rollback()
|
||||
info = await storage.stat_object(key)
|
||||
if info is None or info.size_bytes != result.size_bytes or info.content_type != result.content_type:
|
||||
raise unavailable('Оригинал временно недоступен')
|
||||
if (
|
||||
info is None
|
||||
or info.size_bytes != result.size_bytes
|
||||
or info.content_type != result.content_type
|
||||
):
|
||||
raise unavailable("Оригинал временно недоступен")
|
||||
stream = await storage.open_object(key)
|
||||
return result, stream
|
||||
|
||||
|
||||
async def validate_message_attachments(
|
||||
session: AsyncSession, user: User, chat_id: UUID, attachment_ids: list[UUID],
|
||||
session: AsyncSession,
|
||||
user: User,
|
||||
chat_id: UUID,
|
||||
attachment_ids: list[UUID],
|
||||
) -> None:
|
||||
await ensure_chat_member(session, user, chat_id)
|
||||
records = await repository.get_for_chat(session, chat_id, attachment_ids)
|
||||
if len(records) != len(attachment_ids):
|
||||
raise not_found()
|
||||
if any(record.status != 'ready' for record in records):
|
||||
raise conflict('Вложение ещё не готово')
|
||||
if any(record.status != "ready" for record in records):
|
||||
raise conflict("Вложение ещё не готово")
|
||||
|
||||
|
||||
async def reconcile_attachments(
|
||||
session: AsyncSession, storage: MinioStorage, *, batch_size: int = 20,
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage,
|
||||
*,
|
||||
batch_size: int = 20,
|
||||
dry_run: bool = True,
|
||||
) -> CleanupResult:
|
||||
if not 1 <= batch_size <= 100:
|
||||
raise invalid_request('batch_size должен быть от 1 до 100')
|
||||
intents = await repository.stale_uploads(session, storage.settings.cleanup_grace_seconds, batch_size)
|
||||
raise invalid_request("batch_size должен быть от 1 до 100")
|
||||
intents = await repository.stale_uploads(
|
||||
session, storage.settings.cleanup_grace_seconds, batch_size
|
||||
)
|
||||
candidates = deleted = 0
|
||||
for intent in intents:
|
||||
if await repository.get_by_key(session, intent.object_key) is None:
|
||||
|
||||
@@ -10,13 +10,14 @@ from app.errors.exceptions import payload_too_large, unsupported_media_type
|
||||
|
||||
def decode_image(path: Path, content_type: str, max_pixels: int) -> None:
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
with Image.open(path, formats=['PNG', 'JPEG']) as image:
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(path, formats=["PNG", "JPEG"]) as image:
|
||||
if image.width * image.height > max_pixels:
|
||||
raise payload_too_large('Превышен лимит пикселей изображения')
|
||||
if Image.MIME.get(image.format) != content_type:
|
||||
raise unsupported_media_type('Содержимое не соответствует Content-Type')
|
||||
raise payload_too_large("Превышен лимит пикселей изображения")
|
||||
image_format = image.format
|
||||
if image_format is None or Image.MIME.get(image_format) != content_type:
|
||||
raise unsupported_media_type("Содержимое не соответствует Content-Type")
|
||||
image.verify()
|
||||
# Для JPEG одной verify() недостаточно: декодировать весь оригинал.
|
||||
with Image.open(path, formats=['PNG', 'JPEG']) as image:
|
||||
with Image.open(path, formats=["PNG", "JPEG"]) as image:
|
||||
image.load()
|
||||
|
||||
+16
-6
@@ -8,24 +8,34 @@ import unicodedata
|
||||
from anyio import CancelScope
|
||||
|
||||
from app.core.s3 import S3Settings
|
||||
from app.errors.exceptions import image_validation_error, invalid_request, payload_too_large
|
||||
from app.errors.exceptions import (
|
||||
image_validation_error,
|
||||
invalid_request,
|
||||
payload_too_large,
|
||||
)
|
||||
from app.errors.handlers import operation_timeout
|
||||
|
||||
|
||||
def validate_filename(filename: str) -> None:
|
||||
if not 1 <= len(filename) <= 255 or any(
|
||||
char in '/\\' or unicodedata.category(char) in {'Cc', 'Cf', 'Cs'} for char in filename
|
||||
char in "/\\" or unicodedata.category(char) in {"Cc", "Cf", "Cs"}
|
||||
for char in filename
|
||||
):
|
||||
raise invalid_request('Недопустимое имя файла')
|
||||
raise invalid_request("Недопустимое имя файла")
|
||||
|
||||
|
||||
async def validate_image(path: Path, content_type: str, settings: S3Settings) -> None:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable, '-m', 'app.core.image_worker', str(path), content_type,
|
||||
str(settings.max_image_pixels), stdout=asyncio.subprocess.DEVNULL,
|
||||
sys.executable,
|
||||
"-m",
|
||||
"app.core.image_worker",
|
||||
str(path),
|
||||
content_type,
|
||||
str(settings.max_image_pixels),
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
error = payload_too_large('Превышен бюджет проверки изображения')
|
||||
error = payload_too_large("Превышен бюджет проверки изображения")
|
||||
try:
|
||||
async with operation_timeout(settings.image_timeout_seconds, error):
|
||||
code = await process.wait()
|
||||
|
||||
Reference in New Issue
Block a user