Files
mtusi2026lab4/tests/concurrent_uploads.py
T

54 lines
2.5 KiB
Python

"""Two payload sizes, ten simultaneous uploads, two rounds per size."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import io
import json
from pathlib import Path
import sys
import threading
import time
from PIL import Image
sys.path.insert(0,str(Path(__file__).resolve().parent))
from client import Client,check,run
def main():
c=Client('http://lb:8080',timeout=30)
alice,bob,eve,chat=c.bootstrap()
phases=[]
for width in (512,1536):
stream=io.BytesIO()
Image.new('RGB',(width,width),'navy').save(stream,'PNG',compress_level=0)
payload=stream.getvalue()
checksum=hashlib.sha256(payload).hexdigest()
samples=[]
started=time.time()
for repeat in range(2):
barrier=threading.Barrier(10)
def worker(index):
local=Client(c.base,timeout=45)
barrier.wait()
t=time.monotonic()
result=local.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=concurrent.png',201,
actor=alice,raw=payload,headers={'Content-Type':'image/png'},schema='Attachment')
att=result['json']
check(att['sha256']==checksum and att['size_bytes']==len(payload),'upload metadata mismatch')
return {'elapsed_ms':round((time.monotonic()-t)*1000,3),'instance':result['headers']['X-Instance-Id'],'id':att['id']}
with ThreadPoolExecutor(max_workers=10) as pool:
samples.extend(pool.map(worker,range(10)))
finished=time.time()
instances=sorted({r['instance'] for r in samples})
check(len(instances)>=2,'did not observe two upload processes')
downloaded=c.call('GET','/api/v1/attachments/'+samples[-1]['id']+'/content',actor=bob)
check(downloaded['bytes']==payload,'concurrent upload changed original')
latency=sorted(r['elapsed_ms'] for r in samples)
phases.append({'width':width,'height':width,'size_bytes':len(payload),'concurrency':10,'rounds':2,
'successful_uploads':len(samples),'errors':0,'started_unix':started,'finished_unix':finished,
'elapsed_seconds':round(finished-started,6),'successful_rps':round(len(samples)/(finished-started),3),
'latency_ms':{'p50':latency[9],'p95':latency[18],'p99':latency[19]},
'observed_instances':instances,'individual_requests':samples})
print(json.dumps({'status':'PASS','phases':phases},indent=2))
if __name__=='__main__':
run(main)