Files
mtusi2026lab6/tests/attachment_failover.py
T

46 lines
1.9 KiB
Python

"""Stop the exact API replica which accepted the image; preserve original bytes."""
import os
import subprocess
import time
from pathlib import Path
from client import Client, Failure, arguments, check, run
def main():
args = arguments('Attachment download after stopping the uploading replica')
c = Client(args.base_url, args.ca_file)
alice, bob, _, chat = c.bootstrap()
content = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png',
202, actor=alice, raw=content, headers={'Content-Type': 'image/png'},
schema='Attachment')
att = uploaded['json']
c.message(alice, chat, '', attachments=[att['id']])
c.wait_ready(alice, att)
target = uploaded['headers']['X-Instance-Id']
subprocess.run(['scripts/stop-one.sh'], check=True,
env=dict(os.environ, TARGET_INSTANCE_ID=target),
stdout=subprocess.DEVNULL)
deadline = time.monotonic() + 15
try:
while True:
try:
downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
break
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(.2)
check(downloaded['bytes'] == content, 'original lost after uploader replica stopped')
check(downloaded['headers']['X-Instance-Id'] != target, 'download used stopped replica')
print('PASS: exact uploading replica stopped; another replica returns identical original')
finally:
# Restore the two-replica development stack for subsequent work.
subprocess.run(['docker', 'compose', 'up', '-d', '--wait', 'api'], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if __name__ == '__main__':
run(main)