Add bounded private image upload with safe S3 persistence
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
"""Ten concurrent bounded PNG uploads plus Docker memory samples; BASE_URL overrides localhost:8080."""
|
||||
|
||||
import csv
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
API_NAMES = ("mtusi2026lab4-api-1", "mtusi2026lab4-api-2")
|
||||
EVIDENCE = ROOT / "evidence/upload-memory-2026-10-02.csv"
|
||||
|
||||
|
||||
def png_chunk(name: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + name + data + struct.pack(">I", zlib.crc32(name + data))
|
||||
|
||||
|
||||
def large_png() -> bytes:
|
||||
width, height = 2048, 1536
|
||||
rows = b"".join(b"\0" + os.urandom(width * 3) for _ in range(height))
|
||||
return b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + png_chunk(b"IDAT", zlib.compress(rows, 1)) + png_chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def mib(text: str) -> float:
|
||||
match = re.fullmatch(r"([0-9.]+)(B|KiB|MiB|GiB)", text.strip())
|
||||
if not match:
|
||||
raise ValueError("unexpected Docker memory unit")
|
||||
return float(match.group(1)) * {"B": 1 / 1048576, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}[match.group(2)]
|
||||
|
||||
|
||||
def memory_samples(elapsed: float) -> list[tuple[float, str, float, float]]:
|
||||
command = ["rtk", "proxy", "docker", "stats", "--no-stream", "--format", "{{.Name}},{{.MemUsage}}", *API_NAMES]
|
||||
output = subprocess.run(command, check=True, capture_output=True, text=True, timeout=10).stdout
|
||||
rows = []
|
||||
for line in output.splitlines():
|
||||
name, usage = line.split(",", 1)
|
||||
used, limit = usage.split("/", 1)
|
||||
rows.append((round(elapsed, 3), name, round(mib(used), 3), round(mib(limit), 3)))
|
||||
if len(rows) != 2:
|
||||
raise AssertionError("expected two API container memory samples")
|
||||
return rows
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = Client(timeout=60)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
data = large_png()
|
||||
if len(data) > 10 * 1024 * 1024:
|
||||
raise AssertionError("synthetic PNG exceeds upload limit")
|
||||
expected_hash = hashlib.sha256(data).hexdigest()
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def send(index: int) -> dict:
|
||||
barrier.wait(timeout=10)
|
||||
result = Client(timeout=60).call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=load-{index}.png", 201,
|
||||
actor=actor, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment",
|
||||
)["json"]
|
||||
if result["sha256"] != expected_hash or result["size_bytes"] != len(data):
|
||||
raise AssertionError("upload bytes/hash mismatch")
|
||||
return result
|
||||
|
||||
start = time.monotonic()
|
||||
rows = memory_samples(0)
|
||||
with ThreadPoolExecutor(max_workers=10) as workers:
|
||||
futures = [workers.submit(send, index) for index in range(10)]
|
||||
while not all(future.done() for future in futures):
|
||||
rows.extend(memory_samples(time.monotonic() - start))
|
||||
results = [future.result() for future in futures]
|
||||
rows.extend(memory_samples(time.monotonic() - start))
|
||||
if len({result["id"] for result in results}) != 10:
|
||||
raise AssertionError("uploads did not create ten unique attachments")
|
||||
EVIDENCE.parent.mkdir(exist_ok=True)
|
||||
with EVIDENCE.open("w", newline="") as target:
|
||||
writer = csv.writer(target, lineterminator="\n")
|
||||
writer.writerow(("seconds", "container", "used_mib", "limit_mib"))
|
||||
writer.writerows(rows)
|
||||
peaks = {name: max(row[2] for row in rows if row[1] == name) for name in API_NAMES}
|
||||
print(f"PASS: 10/10 uploads; PNG={len(data)} bytes; elapsed={time.monotonic()-start:.3f}s; peaks={peaks}; evidence={EVIDENCE.name}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user