lab4: память загрузок и S3 под лимитом, документация защиты

- тело загрузки: один буфер ровно Content-Length, без копий до S3 и djpeg;
- PNG: zlib получает вход кусками по 64 KiB (unconsumed_tail копировал остаток IDAT);
- djpeg, убитый OOM-killer'ом, -> 503 (ресурсы сервера), а не 415;
- api: memswap_limit = memory (жёсткий лимит без swap); S3: GOMEMLIMIT и лимиты
  одновременных загрузок SeaweedFS, память 1g;
- docs: CONSISTENCY.md, DEFENSE.md, WINDOWS.md, DATA_MODEL.md под lab4;
  scripts/demo_attachments.py для сценария защиты; CI и collect_evidence под lab4;
- bench/reconcile_faults.py: отчёты трека 2 (ошибки с обеих сторон, прерванный apply).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexey Bodanyuk
2026-10-25 14:21:43 +03:00
co-authored by Claude Opus 5.5
parent a2d867bec6
commit 4ea6924db1
18 changed files with 701 additions and 120 deletions
+29 -15
View File
@@ -164,7 +164,7 @@ class Busy(Unavailable):
@dataclass
class Upload:
data: bytes
data: bytearray
info: images.ImageInfo
sha256: bytes
@@ -227,14 +227,19 @@ def declared_length(request: Request, limit: int) -> int | None:
return length
async def read_image(reader: BodyReader, settings: Settings, declared: str, verify_slots: asyncio.Semaphore) -> Upload:
"""Body -> verified image. Memory: at most MAX_UPLOAD_BYTES per upload (bytearray); the format
and the pixel count are known after the first bytes, so a picture that is too big or not a
PNG/JPEG is rejected without reading/decoding the rest."""
async def read_image(reader: BodyReader, settings: Settings, declared: str, verify_slots: asyncio.Semaphore,
length: int | None) -> Upload:
"""Body -> verified image. Memory: ONE buffer of at most MAX_UPLOAD_BYTES per upload - exactly
Content-Length bytes allocated once when the length is declared (no growth, no final copy);
it is passed as is to the checks and to the S3 PUT. The format and the pixel count are known
after the first bytes, so a picture that is too big or not a PNG/JPEG is rejected without
reading/decoding the rest."""
loop = asyncio.get_running_loop()
deadline = loop.time() + settings.upload_read_timeout_seconds
limit = settings.max_upload_bytes
buffer = bytearray()
buffer = bytearray(length) if length else bytearray()
view = memoryview(buffer) if length else None
filled = 0
digest = hashlib.sha256()
info: images.ImageInfo | None = None
while True:
@@ -247,27 +252,36 @@ async def read_image(reader: BodyReader, settings: Settings, declared: str, veri
raise InvalidRequest("Тело запроса не получено вовремя") from None
if chunk is None:
break
if len(buffer) + len(chunk) > limit:
if filled + len(chunk) > (length or limit):
raise PayloadTooLarge(f"Файл больше {limit} байт")
buffer += chunk
if view is not None:
view[filled:filled + len(chunk)] = chunk
else:
buffer += chunk
filled += len(chunk)
digest.update(chunk)
if info is None and buffer:
info = _sniff(buffer, settings, declared)
if not buffer:
if info is None and filled:
info = _sniff(view[:filled] if view is not None else buffer, settings, declared)
if view is not None:
view.release()
if not filled:
raise InvalidRequest("Тело запроса пустое: нужны байты изображения")
if length and filled != length:
raise InvalidRequest("Тело запроса короче Content-Length")
if info is None:
raise UnsupportedMediaType("Файл не является корректным изображением PNG или JPEG")
data = bytes(buffer)
del buffer
try:
async with verify_slots:
await images.verify(data, info, timeout=settings.image_verify_timeout_seconds,
await images.verify(buffer, info, timeout=settings.image_verify_timeout_seconds,
jpeg_max_memory_mb=settings.jpeg_max_memory_mb)
except images.ImageError as exc:
raise _image_error(exc) from None
except asyncio.TimeoutError:
raise UnsupportedMediaType("Изображение не удалось проверить за отведённое время") from None
return Upload(data, info, digest.digest())
except (images.VerifierUnavailable, MemoryError):
log.warning("image_verifier_unavailable", extra={"fields": {"type": info.content_type, "size": filled}})
raise Busy("Не хватило ресурсов для проверки изображения, повторите позже") from None
return Upload(buffer, info, digest.digest())
def _sniff(buffer: bytearray, settings: Settings, declared: str) -> images.ImageInfo | None: