Обновила storage/postgres.py и attachments.py
This commit is contained in:
+48
-32
@@ -1,4 +1,4 @@
|
||||
"""Вложения (lab4): синхронный binary upload PNG/JPEG, авторизованный download."""
|
||||
"""Вложения (lab5): upload → 202 queued, async worker, download вариантов."""
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
@@ -11,6 +11,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from ..models.schemas import Attachment, User
|
||||
from ..storage import s3
|
||||
@@ -22,6 +23,7 @@ router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
||||
|
||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
PIPELINE_VERSION = 1
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
@@ -52,11 +54,7 @@ def _detect_content_type(data: bytes) -> Optional[str]:
|
||||
|
||||
|
||||
def _validate_image(data: bytes) -> str:
|
||||
"""MIME по содержимому + лимит пикселей + полная проверка декодирования.
|
||||
|
||||
Полное декодирование (load) выполняется через Pillow, чтобы отвергнуть
|
||||
повреждённые/обрезанные файлы, которые open() принимает по заголовку.
|
||||
"""
|
||||
"""MIME по содержимому + лимит пикселей + полная проверка декодирования."""
|
||||
ctype = _detect_content_type(data)
|
||||
if ctype is None:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
@@ -67,14 +65,10 @@ def _validate_image(data: bytes) -> str:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
if width * height > MAX_IMAGE_PIXELS:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
# Полное декодирование всех данных: битый IDAT / обрезанный файл
|
||||
# поднимут OSError/ValueError и будут отвергнуты как 415.
|
||||
img.load()
|
||||
except HTTPException:
|
||||
raise
|
||||
except Image.DecompressionBombError:
|
||||
# Pillow защищается от «бомб» по собственному порогу: для нас
|
||||
# это превышение лимита пикселей → 413.
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
except Exception:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
@@ -83,9 +77,9 @@ def _validate_image(data: bytes) -> str:
|
||||
|
||||
@router.post(
|
||||
path="/chats/{chat_id}/attachments",
|
||||
summary="Принять один PNG/JPEG, до 10 MiB",
|
||||
summary="Принять один PNG/JPEG, до 10 MiB (lab5: 202 queued)",
|
||||
response_model=Attachment,
|
||||
status_code=201,
|
||||
status_code=202,
|
||||
)
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
@@ -96,7 +90,6 @@ async def upload_attachment(
|
||||
_require_member(chat_id, user.id)
|
||||
safe_name = _validate_filename(filename)
|
||||
|
||||
# Content-Length — быстрая отсечка; не доверяем полностью.
|
||||
cl = request.headers.get("content-length")
|
||||
if cl is not None:
|
||||
try:
|
||||
@@ -105,7 +98,6 @@ async def upload_attachment(
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
# Потоковое чтение с жёстким лимитом.
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
async for chunk in request.stream():
|
||||
@@ -119,16 +111,15 @@ async def upload_attachment(
|
||||
if not body:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
# Pillow — в threadpool, чтобы не блокировать event loop.
|
||||
content_type = await run_in_threadpool(_validate_image, body)
|
||||
sha256 = hashlib.sha256(body).hexdigest()
|
||||
|
||||
attachment_id = uuid4()
|
||||
object_key = s3.original_key(chat_id, attachment_id)
|
||||
staging_key = s3.staging_key(chat_id, attachment_id)
|
||||
|
||||
# 1) Сначала сохраняем в S3. Если следующий шаг упадёт — компенсируем.
|
||||
# 1) Durable staging в S3 (приватный prefix).
|
||||
try:
|
||||
await run_in_threadpool(s3.put_bytes, object_key, body, content_type)
|
||||
await run_in_threadpool(s3.put_bytes, staging_key, body, content_type)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
@@ -141,19 +132,31 @@ async def upload_attachment(
|
||||
content_type=content_type,
|
||||
size_bytes=len(body),
|
||||
sha256=sha256,
|
||||
status="ready",
|
||||
status="queued",
|
||||
variants=[],
|
||||
error_code=None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
# 2) INSERT в БД. При ЛЮБОМ исключении удаляем S3-объект (компенсация).
|
||||
job_id = uuid4()
|
||||
outbox_payload = {
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": PIPELINE_VERSION,
|
||||
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
# 2) INSERT attachment + outbox в ОДНОЙ транзакции.
|
||||
# При сбое — компенсация: удаляем staging.
|
||||
try:
|
||||
await run_in_threadpool(storage.create_attachment, att, object_key)
|
||||
await run_in_threadpool(
|
||||
storage.create_attachment_queued, att, staging_key, outbox_payload
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
await run_in_threadpool(s3.delete_object, object_key)
|
||||
await run_in_threadpool(s3.delete_object, staging_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
@@ -180,15 +183,16 @@ def get_attachment(
|
||||
|
||||
@router.get(
|
||||
path="/attachments/{attachment_id}/content",
|
||||
summary="Скачать байты через авторизованный API",
|
||||
summary="Скачать байты (original или variant) через авторизованный API",
|
||||
)
|
||||
def download_attachment(
|
||||
attachment_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
variant: str = Query("original"),
|
||||
):
|
||||
if variant != "original":
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
if variant not in ("original", "thumbnail", "crop", "optimized"):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
@@ -197,16 +201,28 @@ def download_attachment(
|
||||
if att.status != "ready":
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
try:
|
||||
data, ctype = s3.get_object(object_key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Объект отсутствует при готовых метаданных: 404.
|
||||
if exc.__class__.__name__ == "NoSuchKey":
|
||||
if variant == "original":
|
||||
key = object_key
|
||||
ctype_expected = att.content_type
|
||||
else:
|
||||
vs = [v for v in att.variants if v.name == variant]
|
||||
if not vs:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
v = vs[0]
|
||||
key = s3.variant_key(att.chat_id, att.id, variant)
|
||||
ctype_expected = v.content_type
|
||||
|
||||
try:
|
||||
data, ctype = s3.get_object(key)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code in ("404", "NoSuchKey", "NotFound"):
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=ctype,
|
||||
headers={"Content-Length": str(len(data))},
|
||||
media_type=ctype or ctype_expected,
|
||||
)
|
||||
Reference in New Issue
Block a user