Files
mtusi2026lab4-fork/app/upload.py
daniil_sobolev 747ca222e5 Implement lab4 attachments on RustFS for grade 4.
Carry over lab3 HA stack and add private S3 storage, Attachment API, orphan compensation/reaper, own tests, and evidence for smoke/persistence/failover.
2026-11-12 20:41:02 +03:00

42 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Потоковое чтение тела загрузки с жёстким лимитом размера."""
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)