forked from mtusi2026/mtusi2026lab4
60 lines
3.7 KiB
Python
60 lines
3.7 KiB
Python
"""Additional contract and cross-replica concurrency tests. No secrets in output."""
|
|
from client import Client, check, run
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from pathlib import Path
|
|
import uuid, json, time, subprocess, threading, zlib, struct, os
|
|
|
|
def main():
|
|
c=Client(timeout=30)
|
|
a,b,e,chat=c.bootstrap()
|
|
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=a,body={'text':True},headers={'Idempotency-Key':uuid.uuid4().hex})
|
|
data=Path('tests/fixtures/sample.png').read_bytes()
|
|
path='/api/v1/chats/'+chat['id']+'/attachments?filename=test.png'
|
|
def upload(raw=data, mime='image/png', expected=201, target=path):
|
|
return c.call('POST',target,expected,actor=a,raw=raw,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None)
|
|
upload(data,'image/jpeg',415)
|
|
upload(data[:40],expected=415)
|
|
ihdr=struct.pack('>IIBBBBB',7000,7000,8,2,0,0,0)
|
|
bomb=b'\x89PNG\r\n\x1a\n'+struct.pack('>I',13)+b'IHDR'+ihdr+struct.pack('>I',zlib.crc32(b'IHDR'+ihdr)&0xffffffff)
|
|
upload(bomb,expected=413)
|
|
upload(b'x'*10485761,expected=413)
|
|
upload(target=path.replace('test.png','bad%7F.png'),expected=400)
|
|
att=upload()['json']
|
|
other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'other','member_ids':[a['id']]},schema='Chat')['json']
|
|
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=a,body={'text':'x','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
|
for ids in ([att['id']]*2,[str(uuid.uuid4())]):
|
|
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400 if len(ids)==2 else 404,actor=a,body={'text':'x','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex})
|
|
print('PASS negative: MIME, corrupt, oversized, filename, duplicate/unknown/cross-chat attachments')
|
|
key=uuid.uuid4().hex
|
|
def message(_):
|
|
return c.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=a,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':key},schema='Message')
|
|
with ThreadPoolExecutor(max_workers=12) as pool:
|
|
replies=list(pool.map(message,range(24)))
|
|
check(len({r['json']['id'] for r in replies})==1,'duplicate message')
|
|
instances={r['headers']['X-Instance-Id'] for r in replies}
|
|
check(len(instances)>=2,'need two replicas')
|
|
print('PASS 24 simultaneous idempotent requests across',len(instances),'replicas; one message')
|
|
def chunk(kind, body):
|
|
return struct.pack('>I',len(body))+kind+body+struct.pack('>I',zlib.crc32(kind+body)&0xffffffff)
|
|
width=1700
|
|
large=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,width,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(b''.join(b'\0'+os.urandom(width*3) for _ in range(width))))+chunk(b'IEND',b'')
|
|
samples=[]; done=threading.Event()
|
|
def sample():
|
|
while not done.is_set():
|
|
samples.append(subprocess.check_output(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}}'],text=True))
|
|
sampler=threading.Thread(target=sample); sampler.start()
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
started=time.monotonic(); results=list(pool.map(lambda _:upload(large),range(20)))
|
|
check(len({r['json']['id'] for r in results})==20,'uploads collided')
|
|
done.set(); sampler.join()
|
|
print('image_bytes=',len(large),'memory_samples=',samples)
|
|
print('PASS 20 uploads concurrency=10 elapsed_seconds=',round(time.monotonic()-started,3))
|
|
print(subprocess.check_output(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}}'],text=True))
|
|
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=a)
|
|
for _ in range(10): c.call('GET','/api/v1/users/me',401,actor=a)
|
|
print('PASS logout across replicas')
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|
|
|