Files
mtusi2026lab4/tests/upload_burst.py

34 lines
1.9 KiB
Python

#!/usr/bin/env python3
"""Send ten concurrent near-maximum-safe PNG uploads and summarize traffic/time."""
from concurrent.futures import ThreadPoolExecutor, as_completed
import hashlib, random, struct, time, zlib
from client import Client, arguments, check, run
def png_noise(width=1600,height=1600):
# RGB rows, filter type 0. Deterministic PRNG-free byte pattern keeps this
# fixture reproducible and incompressible enough to exercise the 1 MiB spool.
rng=random.Random(20261106)
raw=b''.join(b'\0'+rng.randbytes(width*3) for _ in range(height))
def chunk(tag,data): return struct.pack('!I',len(data))+tag+data+struct.pack('!I',zlib.crc32(tag+data)&0xffffffff)
data=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!2I5B',width,height,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(raw,1))+chunk(b'IEND',b'')
check(len(data)<=10*1024*1024,'generated PNG exceeds upload limit')
return data
def main():
args=arguments('Lab 4 concurrent upload memory/throughput sample')
c=Client(args.base_url,args.ca_file,timeout=30)
alice,bob,eve,chat=c.bootstrap(); data=png_noise(); sha=hashlib.sha256(data).hexdigest()
def upload(i):
return c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=burst-'+str(i)+'.png',201,actor=alice,raw=data,headers={'Content-Type':'image/png'},schema='Attachment')['json']
start=time.monotonic(); uploaded=[]
with ThreadPoolExecutor(max_workers=10) as pool:
futures=[pool.submit(upload,i) for i in range(10)]
for future in as_completed(futures): uploaded.append(future.result())
elapsed=time.monotonic()-start
check(len(uploaded)==10 and all(x['sha256']==sha and x['size_bytes']==len(data) for x in uploaded),'upload result/checksum mismatch')
print('uploads=10 concurrency=10 size_bytes=%d total_bytes=%d sha256=%s elapsed_seconds=%.3f throughput_mib_s=%.2f' % (len(data),len(data)*10,sha,elapsed,len(data)*10/1048576/elapsed))
if __name__=='__main__': run(main)