forked from mtusi2026/mtusi2026lab4
4
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
"""Логика вложений: проверка изображений, загрузка в S3, компенсация."""
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from . import config, db, repo, s3
|
||||
from .errors import ApiError, bad_request, not_found
|
||||
|
||||
log = logging.getLogger("attachments")
|
||||
|
||||
ALLOWED_FORMATS = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
||||
|
||||
# PIL отказывается читать изображение с числом пикселей больше лимита,
|
||||
# ещё до полной распаковки — это защита от decompression bomb.
|
||||
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
||||
|
||||
|
||||
def validate_filename(filename):
|
||||
"""Отображаемое имя; ключ S3 формирует сервер."""
|
||||
if not isinstance(filename, str) or not (1 <= len(filename) <= 255):
|
||||
raise bad_request("Некорректное имя файла")
|
||||
if any(c in filename for c in ("/", "\\", "\x00")) or any(ord(c) < 0x20 for c in filename):
|
||||
raise bad_request("Недопустимое имя файла")
|
||||
return filename
|
||||
|
||||
|
||||
def _inspect_image(fileobj):
|
||||
"""Формат и размеры из заголовка, затем целостность через verify().
|
||||
|
||||
verify() не декодирует пиксели, только проверяет CRC/структуру.
|
||||
"""
|
||||
try:
|
||||
with Image.open(fileobj) as img:
|
||||
fmt = img.format
|
||||
width, height = img.size
|
||||
img.verify()
|
||||
except UnidentifiedImageError:
|
||||
raise ApiError(415, "unsupported_media_type", "Неизвестный формат изображения")
|
||||
except Image.DecompressionBombError:
|
||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||||
except Exception:
|
||||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
||||
|
||||
if fmt not in ALLOWED_FORMATS:
|
||||
raise ApiError(415, "unsupported_media_type", "Ожидается PNG или JPEG")
|
||||
if width <= 0 or height <= 0:
|
||||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
||||
if width * height > config.MAX_IMAGE_PIXELS:
|
||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||||
return ALLOWED_FORMATS[fmt]
|
||||
|
||||
|
||||
def inspect_image_file(fileobj, total_bytes):
|
||||
"""Проверяет уже прочитанное тело. Возвращает фактический content_type.
|
||||
|
||||
fileobj должен быть seekable; после вызова позиция = 0.
|
||||
"""
|
||||
if total_bytes == 0:
|
||||
raise bad_request("Пустой файл")
|
||||
if total_bytes > config.MAX_UPLOAD_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||
fileobj.seek(0)
|
||||
content_type = _inspect_image(fileobj)
|
||||
fileobj.seek(0)
|
||||
return content_type
|
||||
|
||||
|
||||
def upload_stream(chat_id, owner_id, filename, fileobj, total_bytes, digest, content_type):
|
||||
"""pending в БД → S3 PUT → ready. fileobj уже провалидирован и на позиции 0."""
|
||||
validate_filename(filename)
|
||||
object_key = "originals/%s/%s" % (chat_id, uuid.uuid4().hex)
|
||||
|
||||
with db.connection() as conn:
|
||||
if not repo.is_member(conn, chat_id, owner_id):
|
||||
raise not_found()
|
||||
row = repo.insert_attachment_pending(
|
||||
conn, chat_id, owner_id, filename, content_type, total_bytes, digest, object_key
|
||||
)
|
||||
attachment_id = row["id"]
|
||||
|
||||
try:
|
||||
fileobj.seek(0)
|
||||
s3.put_object(object_key, fileobj, content_type, content_length=total_bytes)
|
||||
except Exception as exc:
|
||||
log.warning("S3 PUT failed for %s: %s", attachment_id, type(exc).__name__)
|
||||
# Компенсация: удаляем возможный частичный объект.
|
||||
s3.delete_object(object_key)
|
||||
with db.connection() as conn:
|
||||
repo.mark_attachment_failed(conn, attachment_id, "storage_unavailable")
|
||||
raise ApiError(503, "unavailable", "Хранилище временно недоступно")
|
||||
|
||||
try:
|
||||
with db.connection() as conn:
|
||||
ready = repo.mark_attachment_ready(conn, attachment_id)
|
||||
except Exception:
|
||||
# Объект уже в S3, но COMMIT в БД не прошёл → orphan-pending.
|
||||
# scripts/reconcile_s3.py найдёт и удалит после grace period.
|
||||
log.error("S3 object %s left orphaned after DB failure", object_key)
|
||||
raise
|
||||
if ready is None:
|
||||
raise ApiError(409, "conflict", "Вложение уже в обработке")
|
||||
return repo.attachment_json(ready)
|
||||
|
||||
|
||||
def download(attachment_id, user_id):
|
||||
"""Возвращает (metadata_row, s3_body) или 404/409/503."""
|
||||
with db.connection() as conn:
|
||||
row = repo.get_attachment_for_member(conn, attachment_id, user_id)
|
||||
if row is None:
|
||||
raise not_found()
|
||||
if row["status"] == "failed":
|
||||
raise ApiError(409, "conflict", "Вложение недоступно")
|
||||
if row["status"] != "ready":
|
||||
raise ApiError(409, "conflict", "Вложение ещё не готово")
|
||||
try:
|
||||
body = s3.get_object(row["object_key"])
|
||||
except Exception as exc:
|
||||
log.warning("S3 GET failed for %s: %s", attachment_id, type(exc).__name__)
|
||||
raise ApiError(503, "unavailable", "Хранилище временно недоступно")
|
||||
return row, body
|
||||
Reference in New Issue
Block a user