forked from mtusi2026/mtusi2026lab4
Carry over lab3 HA stack and add private S3 storage, Attachment API, orphan compensation/reaper, own tests, and evidence for smoke/persistence/failover.
42 lines
1.5 KiB
Python
42 lines
1.5 KiB
Python
"""Потоковое чтение тела загрузки с жёстким лимитом размера."""
|
||
from __future__ import annotations
|
||
|
||
from fastapi import Request
|
||
|
||
from app.config import settings
|
||
from app.errors import invalid_request, payload_too_large
|
||
|
||
|
||
async def read_body_limited(request: Request) -> bytes:
|
||
"""Читает тело чанками; обрывает накопление при превышении MAX_UPLOAD_BYTES.
|
||
|
||
При слишком большом Content-Length дренируем поток (без хранения),
|
||
чтобы клиент успел получить 413, а не ConnectionReset.
|
||
"""
|
||
max_bytes = settings.max_upload_bytes
|
||
declared = request.headers.get("content-length")
|
||
if declared is not None:
|
||
try:
|
||
length = int(declared)
|
||
except ValueError as exc:
|
||
raise invalid_request("Неверный Content-Length") from exc
|
||
if length > max_bytes:
|
||
async for _chunk in request.stream():
|
||
pass
|
||
raise payload_too_large("Файл больше 10 MiB")
|
||
|
||
chunks: list[bytes] = []
|
||
total = 0
|
||
async for chunk in request.stream():
|
||
if not chunk:
|
||
continue
|
||
total += len(chunk)
|
||
if total > max_bytes:
|
||
async for _rest in request.stream():
|
||
pass
|
||
raise payload_too_large("Файл больше 10 MiB")
|
||
chunks.append(chunk)
|
||
if total < 1:
|
||
raise invalid_request("Пустое тело запроса")
|
||
return b"".join(chunks)
|