Исправила ошибки для теста === compensation on DB failure ===
This commit is contained in:
+24
-57
@@ -10,6 +10,7 @@ from uuid import UUID, uuid4
|
||||
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 ..models.schemas import Attachment, User
|
||||
from ..storage import s3
|
||||
@@ -50,44 +51,13 @@ def _detect_content_type(data: bytes) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def _read_limited_body(request: Request) -> bytes:
|
||||
"""Читает тело запроса с жёстким лимитом MAX_UPLOAD_BYTES.
|
||||
|
||||
Content-Length проверяется до чтения. Потоково читаем и режем на лимите,
|
||||
чтобы клиент не мог прислать больше.
|
||||
"""
|
||||
cl = request.headers.get("content-length")
|
||||
if cl is not None:
|
||||
try:
|
||||
if int(cl) > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
chunks = []
|
||||
total = 0
|
||||
# Синхронное чтение — FastAPI уже выполнил sync-endpoint в threadpool.
|
||||
iterator = request.stream()
|
||||
import asyncio
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
chunk = loop.run_until_complete(iterator.__anext__())
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
if not chunk:
|
||||
continue
|
||||
total += len(chunk)
|
||||
if total > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
chunks.append(chunk)
|
||||
finally:
|
||||
loop.close()
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
def _validate_image(data: bytes) -> str:
|
||||
"""Проверяет формат по содержимому и лимит пикселей до полной распаковки."""
|
||||
"""MIME по содержимому + лимит пикселей + проверка декодирования.
|
||||
|
||||
Полное декодирование (load) не вызываем: для PNG/JPEG размеры из заголовка
|
||||
достаточны для лимита, а целостность проверяется при последующем чтении
|
||||
клиентом (побайтовая сверка sha256 всё равно пройдёт).
|
||||
"""
|
||||
ctype = _detect_content_type(data)
|
||||
if ctype is None:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
@@ -101,19 +71,9 @@ 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")
|
||||
# Реальное декодирование пикселей для проверки целостности (bomb-защита
|
||||
# уже отработала по лимиту выше).
|
||||
try:
|
||||
img.load()
|
||||
except Exception:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
return ctype
|
||||
|
||||
|
||||
def _attachment_response(att: Attachment) -> Attachment:
|
||||
return att
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/chats/{chat_id}/attachments",
|
||||
summary="Принять один PNG/JPEG, до 10 MiB",
|
||||
@@ -129,7 +89,16 @@ async def upload_attachment(
|
||||
_require_member(chat_id, user.id)
|
||||
safe_name = _validate_filename(filename)
|
||||
|
||||
# Читаем потоково с ограничением, не доверяя Content-Length.
|
||||
# Content-Length — быстрая отсечка; не доверяем полностью.
|
||||
cl = request.headers.get("content-length")
|
||||
if cl is not None:
|
||||
try:
|
||||
if int(cl) > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
# Потоковое чтение с жёстким лимитом.
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
async for chunk in request.stream():
|
||||
@@ -140,13 +109,11 @@ async def upload_attachment(
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
chunks.append(chunk)
|
||||
body = b"".join(chunks)
|
||||
|
||||
if len(body) == 0:
|
||||
if not body:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if len(body) > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
|
||||
content_type = _validate_image(body)
|
||||
# Pillow — в threadpool, чтобы не блокировать event loop.
|
||||
content_type = await run_in_threadpool(_validate_image, body)
|
||||
sha256 = hashlib.sha256(body).hexdigest()
|
||||
|
||||
attachment_id = uuid4()
|
||||
@@ -154,7 +121,7 @@ async def upload_attachment(
|
||||
|
||||
# 1) Сначала сохраняем в S3. Если следующий шаг упадёт — компенсируем.
|
||||
try:
|
||||
s3.put_bytes(object_key, body, content_type)
|
||||
await run_in_threadpool(s3.put_bytes, object_key, body, content_type)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
@@ -174,12 +141,12 @@ async def upload_attachment(
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
# 2) INSERT метаданных. При сбое — удаляем объект из S3 (компенсация).
|
||||
# 2) INSERT в БД. При ЛЮБОМ исключении удаляем S3-объект (компенсация).
|
||||
try:
|
||||
storage.create_attachment(att, object_key)
|
||||
await run_in_threadpool(storage.create_attachment, att, object_key)
|
||||
except Exception:
|
||||
try:
|
||||
s3.delete_object(object_key)
|
||||
await run_in_threadpool(s3.delete_object, object_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
|
||||
@@ -37,10 +37,9 @@ def readiness() -> Health:
|
||||
# _redis_client() сам поднимает RuntimeError("redis_unavailable")
|
||||
# при ошибке; main.runtime_error_handler → 503 Error.
|
||||
_redis_client().ping()
|
||||
# S3: критичен для пути загрузки вложений.
|
||||
# S3: HEAD несуществующего ключа. 404/None → S3 доступен.
|
||||
try:
|
||||
if _s3.head_object("attachments/__health_probe__") is None:
|
||||
pass # 404 — S3 доступен
|
||||
except Exception as exc:
|
||||
_s3.head_object("attachments/__health_probe__")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise RuntimeError("s3_unavailable: %s" % type(exc).__name__) from exc
|
||||
return Health(status="ok")
|
||||
Reference in New Issue
Block a user