#!/usr/bin/env python3 """Lab5 track 1: compare API traffic/RAM for proxy vs presigned direct upload.""" from __future__ import annotations import argparse import hashlib import io import json import math import os import re import subprocess import threading import time from PIL import Image from common import HttpClient, assert_status MEM_RE = re.compile(r"([0-9.]+)\s*(B|KiB|MiB|GiB)") def make_png(target_bytes: int) -> bytes: pixels = max(1, target_bytes // 3) width = max(32, int(math.sqrt(pixels * 1.4))) height = max(32, pixels // width) image = Image.frombytes("RGB", (width, height), os.urandom(width * height * 3)) buffer = io.BytesIO() image.save(buffer, format="PNG", compress_level=1) return buffer.getvalue() def api_containers(prefix: str) -> list[str]: try: result = subprocess.run( ["docker", "ps", "--filter", "name=" + prefix, "--format", "{{.Names}}"], capture_output=True, text=True, timeout=10, ) except (OSError, subprocess.SubprocessError): return [] return [line.strip() for line in result.stdout.splitlines() if line.strip()] def api_net_bytes(names: list[str]) -> dict[str, int]: total = 0 for name in names: try: result = subprocess.run( ["docker", "exec", name, "cat", "/proc/net/dev"], capture_output=True, text=True, timeout=10, ) except (OSError, subprocess.SubprocessError): continue for line in result.stdout.splitlines(): if "eth0:" not in line: continue fields = line.split("eth0:")[1].split() # RX bytes is field 0; TX bytes is field 8. total += int(fields[0]) + int(fields[8]) return {"total": total} def memory_mib(text: str) -> float | None: match = MEM_RE.search(text) if not match: return None return float(match.group(1)) * {"B": 1 / 1024 / 1024, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}[match.group(2)] def api_mem_mib(prefix: str) -> float: try: result = subprocess.run( ["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"], capture_output=True, text=True, timeout=10, ) except (OSError, subprocess.SubprocessError): return 0.0 total = 0.0 for line in result.stdout.splitlines(): name, _, mem = line.partition(" ") if prefix in name: value = memory_mib(mem) if value is not None: total += value return total def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") parser.add_argument("--container-prefix", default="mtusi-lab4-api") parser.add_argument("--output", default="") args = parser.parse_args() client = HttpClient(args.base_url) alice, alice_reg = client.register() token = client.login(alice_reg)["token"] status, _h, chat, _r = client.call( "POST", "/api/v1/chats", body={"title": "Transfer comparison", "member_ids": [alice["id"]]}, token=token, ) assert_status(status, 201, "create chat") names = api_containers(args.container_prefix) results = [] for target in (512 * 1024, 4 * 1024 * 1024): content = make_png(target) digest = hashlib.sha256(content).hexdigest() # Proxy: client -> API -> S3, all bytes pass through the API process. before = api_net_bytes(names)["total"] mem_before = api_mem_mib(args.container_prefix) status, _h, _p, _r = client.raw( "POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=proxy.png", data=content, headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"}, timeout=120, ) assert_status(status, 201, "proxy upload") after = api_net_bytes(names)["total"] mem_after = api_mem_mib(args.container_prefix) proxy = { "file_bytes": len(content), "api_network_bytes": after - before, "api_memory_growth_mib": round(max(0.0, mem_after - mem_before), 2), "client_to_api_bytes": len(content), "client_to_s3_bytes": 0, } # Direct: presign, client -> S3, then complete reads the object once to # verify the checksum. The public API never receives the file body. status, _h, presign, _r = client.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments/presign", body={ "filename": "direct.png", "content_type": "image/png", "size_bytes": len(content), "sha256": digest, }, token=token, ) assert_status(status, 201, "presign") status, _h, _p, _r = client.raw( "PUT", presign["upload_url"], data=content, headers=presign["headers"], timeout=120 ) assert_status(status, 200, "direct PUT") before = api_net_bytes(names)["total"] mem_before = api_mem_mib(args.container_prefix) peak = {"value": mem_before} stop = threading.Event() def sampler() -> None: while not stop.is_set(): peak["value"] = max(peak["value"], api_mem_mib(args.container_prefix)) time.sleep(0.1) thread = threading.Thread(target=sampler, daemon=True) thread.start() status, _h, _p, _r = client.call( "POST", "/api/v1/attachments/" + presign["attachment_id"] + "/complete", body={"sha256": digest, "size_bytes": len(content)}, token=token, ) stop.set() thread.join(timeout=2) assert_status(status, 200, "complete") after = api_net_bytes(names)["total"] direct = { "file_bytes": len(content), "api_network_bytes": after - before, "api_memory_peak_mib": round(peak["value"], 2), "api_memory_growth_mib": round(max(0.0, peak["value"] - mem_before), 2), "client_to_api_bytes": 0, "client_to_s3_bytes": len(content), } results.append({"proxy": proxy, "direct": direct}) summary = {"container_prefix": args.container_prefix, "sizes": results} print(json.dumps(summary, ensure_ascii=False, sort_keys=True)) if args.output: with open(args.output, "w", encoding="utf-8") as handle: json.dump(summary, handle, ensure_ascii=False, indent=2, sort_keys=True) print("PASS: measured proxy vs direct API traffic and memory at two file sizes") if __name__ == "__main__": main()