#!/usr/bin/env python3 """Аудит F02: допустимые по контракту progressive JPEG ~40 Мпикс не должны ронять API. docker compose --profile tools run --rm checks /app/student-tests/progressive_upload.py \ --base-url http://lb:8080 --output /app/evidence/progressive-upload.json Файлы маленькие (~0,5–0,9 MB, гладкая картинка), но декодирование progressive JPEG требует буфер коэффициентов всего кадра: 4:2:0 ~140 MiB, 4:4:4 ~250 MiB (замер на Pillow 13). Одновременно загружаются 4 progressive 4:4:4 + 1 progressive 4:2:0 + 1 baseline: при двух репликах за round-robin LB на каждую приходится по 2 тяжёлых декодирования одновременно. Ожидаем: все 202, все ready, thumbnail 256x256. Что реплики API не были убиты (RestartCount, OOMKilled), проверяет хост-обёртка api_negative_lab5.py. """ import argparse import concurrent.futures import io import json import sys import time from pathlib import Path sys.path.insert(0, "/app/tests") from client import Client, check # noqa: E402 from PIL import Image # noqa: E402 SIDE = 6324 # 39 992 976 пикселей (< 40 000 000) def make(kind, seed): g = Image.radial_gradient("L").resize((SIDE, SIDE)) img = Image.merge("RGB", (g, g.rotate(90 * seed), g.transpose(Image.Transpose.FLIP_TOP_BOTTOM))) kw = {"baseline": {}, "progressive_420": {"progressive": True}, "progressive_444": {"progressive": True, "subsampling": 0}}[kind] buf = io.BytesIO() img.save(buf, "JPEG", quality=85, **kw) return buf.getvalue() def main(): p = argparse.ArgumentParser() p.add_argument("--base-url", default="http://lb:8080") p.add_argument("--output") args = p.parse_args() c = Client(args.base_url, timeout=60) alice, bob, _eve, chat = c.bootstrap() files = [("progressive_444", make("progressive_444", i)) for i in range(4)] + \ [("progressive_420", make("progressive_420", 1)), ("baseline", make("baseline", 0))] def up(item): kind, data = item t = time.monotonic() r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%s.jpg" % (chat["id"], kind), [202, 413, 502, 503, 504], actor=alice, raw=data, headers={"Content-Type": "image/jpeg"}, schema="Attachment") return {"kind": kind, "bytes": len(data), "status": r["status"], "seconds": round(time.monotonic() - t, 2), "instance": r["headers"].get("X-Instance-Id"), "id": r["json"]["id"] if r["status"] == 202 else None, "error": r["json"]["error"]["code"] if r["status"] != 202 else None} with concurrent.futures.ThreadPoolExecutor(len(files)) as pool: results = list(pool.map(up, files)) for r in results: print(json.dumps(r), flush=True) for r in results: check(r["status"] == 202, "%s upload: %s %s" % (r["kind"], r["status"], r["error"])) for r in results: att = c.wait_ready(bob, {"id": r["id"]}, wait_seconds=120) thumb = [v for v in att["variants"] if v["name"] == "thumbnail"][0] check((thumb["width"], thumb["height"]) == (256, 256), "thumbnail size") r["ready"] = True if args.output: Path(args.output).write_text(json.dumps({"side": SIDE, "pixels": SIDE * SIDE, "uploads": results}, indent=1) + "\n") print("PASS: %d concurrent ~40 Mpx JPEG (progressive 4:4:4/4:2:0, baseline) -> 202 -> ready" % len(results)) if __name__ == "__main__": main()