Files
mtusi2026lab6/student-tests/durability.py
T

53 lines
2.6 KiB
Python

"""Stop worker, accept queued, restart API/broker, then complete the same attachment."""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client,Failure
def docker(*args):return subprocess.check_output(['docker',*args],text=True).strip()
def main():
c=Client();alice,bob,eve,chat=c.bootstrap();record={}
before=json.loads(subprocess.check_output([sys.executable,'scripts/snapshot.py'],text=True))
try:
docker('compose','stop','worker','dispatcher')
queued,raw=c.attachment(alice,chat)
assert queued['status']=='queued'
message=c.message(alice,chat,'accepted with worker stopped',attachments=[queued['id']])['json']
c.call('GET','/api/v1/attachments/'+queued['id']+'/content',409,actor=bob)
killed=docker('compose','ps','-q','api').splitlines()
for container in killed:docker('kill','--signal=KILL',container)
record['killed_api_containers']=killed
docker('compose','up','-d','--wait','--no-deps','api')
time.sleep(2)
assert c.call('GET','/api/v1/attachments/'+queued['id'],actor=bob,schema='Attachment')['json']['status']=='queued'
docker('compose','up','-d','--no-deps','dispatcher')
deadline=time.monotonic()+10
while int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))<1:
assert time.monotonic()<deadline;time.sleep(.1)
docker('compose','stop','dispatcher')
length_before=int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))
docker('compose','restart','broker')
docker('compose','up','-d','--wait','--no-deps','broker')
length_after=int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))
assert length_after>=length_before>=1
record['stream_entries_before_after_broker_restart']=[length_before,length_after]
docker('compose','up','-d','--no-deps','worker','dispatcher')
ready=c.wait_ready(bob,queued)
assert c.call('GET','/api/v1/attachments/'+queued['id']+'/content',actor=bob)['bytes']==raw
record.update(attachment_id=queued['id'],original_sha256=hashlib.sha256(raw).hexdigest(),status=ready['status'],variants=[v['name'] for v in ready['variants']],old_bearer_survived=True,message_attachment_retained=message['attachment_ids']==[queued['id']])
finally:docker('compose','up','-d','--no-deps','worker','dispatcher')
after=json.loads(subprocess.check_output([sys.executable,'scripts/snapshot.py'],text=True))
record['before']=before;record['after']=after
print(json.dumps(record,indent=2))
if __name__=='__main__':main()