forked from mtusi2026/mtusi2026lab4
127 lines
5.8 KiB
Python
127 lines
5.8 KiB
Python
"""Логика вложений: проверка изображений, загрузка в S3, компенсация."""
|
||
import logging
|
||
import threading
|
||
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 отказывается читать изображение с числом пикселей больше лимита.
|
||
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
||
|
||
# Ограничиваем одновременные декодирования, чтобы пик RAM
|
||
# (≤ MAX_IMAGE_PIXELS × 4 байт на каждое) укладывался в mem_limit контейнера.
|
||
_decode_slots = threading.BoundedSemaphore(3)
|
||
|
||
|
||
def validate_filename(filename):
|
||
"""Отображаемое имя; ключ S3 формирует сервер.
|
||
|
||
Запрещены / \\ NUL и любые control-символы 0x00–0x1F и DEL 0x7F.
|
||
"""
|
||
if not isinstance(filename, str) or not (1 <= len(filename) <= 255):
|
||
raise bad_request("Некорректное имя файла")
|
||
for c in filename:
|
||
if c in ("/", "\\", "\x00") or ord(c) < 0x20 or ord(c) == 0x7F:
|
||
raise bad_request("Недопустимое имя файла")
|
||
return filename
|
||
|
||
|
||
def _inspect_image(fileobj):
|
||
"""Полная валидация: заголовок → лимиты → load().
|
||
|
||
load() декодирует IDAT (PNG) / энтропийные данные (JPEG). Битый поток
|
||
даёт OSError('broken data stream') → 415. Память ограничена
|
||
MAX_IMAGE_PIXELS × 4 байт и семафором _decode_slots.
|
||
"""
|
||
with _decode_slots:
|
||
try:
|
||
with Image.open(fileobj) as img:
|
||
fmt = img.format
|
||
width, height = img.size
|
||
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", "Слишком много пикселей")
|
||
# Полное декодирование: проверяет целостность IDAT-потока,
|
||
# а не только CRC чанков (как verify()).
|
||
img.load()
|
||
return ALLOWED_FORMATS[fmt]
|
||
except UnidentifiedImageError:
|
||
raise ApiError(415, "unsupported_media_type", "Неизвестный формат изображения")
|
||
except Image.DecompressionBombError:
|
||
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||
except (OSError, SyntaxError, ValueError):
|
||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
||
finally:
|
||
fileobj.seek(0)
|
||
|
||
|
||
def inspect_image_file(fileobj, total_bytes):
|
||
"""Проверяет уже прочитанное тело. Возвращает фактический content_type."""
|
||
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)
|
||
return _inspect_image(fileobj)
|
||
|
||
|
||
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:
|
||
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 |