"""Stop the API that accepted a file after its asynchronous job is ready.""" import hashlib import os import subprocess import time from client import Client, arguments, check, run def main(): args=arguments('Upload/download failover on both APIs') c=Client(args.base_url,args.ca_file) alice,bob,eve,chat=c.bootstrap() content=open('tests/fixtures/sample.png','rb').read() path='/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png' for service in ('api1','api2'): cid=subprocess.check_output(['docker','compose','ps','-q',service],text=True).strip() env=subprocess.check_output(['docker','inspect','--format','{{range .Config.Env}}{{println .}}{{end}}',cid],text=True) target=next((line.split('=',1)[1] for line in env.splitlines() if line.startswith('APP_INSTANCE_ID=')),None) check(bool(target),'API instance identity is missing') for _ in range(20): uploaded=c.call('POST',path,202,actor=alice,raw=content,headers={'Content-Type':'image/png'},schema='Attachment') if uploaded['headers']['X-Instance-Id']==target: break else: raise AssertionError('Target API not observed through LB') att=uploaded['json']; c.wait_ready(alice,att) c.message(alice,chat,'',attachments=[att['id']]) started=time.monotonic() try: subprocess.run(['scripts/stop-one.sh'],env=dict(os.environ,TARGET_INSTANCE_ID=target),check=True,stdout=subprocess.DEVNULL) while time.monotonic()-started<10: try: downloaded=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob) except Exception: time.sleep(.2); continue check(downloaded['headers']['X-Instance-Id']!=target,'stopped API still responds') check(downloaded['bytes']==content,'original changed') print('PASS:',service,'downloaded original via other API in',round(time.monotonic()-started,3),'s; SHA-256',hashlib.sha256(content).hexdigest(),flush=True) break else: raise AssertionError('Download did not recover within 10 seconds') finally: subprocess.run(['docker','compose','start',service],check=True) for _ in range(30): health=subprocess.check_output(['docker','inspect','--format','{{.State.Health.Status}}',cid],text=True).strip() if health=='healthy': time.sleep(2); break time.sleep(1) else: raise AssertionError('API did not recover') if __name__=='__main__': run(main)