"""Stop the exact process that served an upload and retrieve the original.""" from hashlib import sha256 import os from pathlib import Path import subprocess import sys from time import monotonic, sleep ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, Failure, arguments, check, run def main(): args = arguments('Download after stopping the uploading replica', lambda parser: parser.add_argument('--action-script', required=True)) client = Client(args.base_url, args.ca_file, timeout=2) alice, bob, _, chat = client.bootstrap() png = (ROOT / 'tests/fixtures/sample.png').read_bytes() response = client.call('POST', f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 201, actor=alice, headers={'Content-Type': 'image/png'}, raw=png, schema='Attachment') target = response['headers']['X-Instance-Id'] attachment = response['json'] script = Path(args.action_script).resolve() check(script.is_file() and os.access(script, os.X_OK), 'action script is not executable') start = monotonic() subprocess.run([str(script)], env={**os.environ, 'TARGET_INSTANCE_ID': target}, check=True, timeout=10) while monotonic() - start < 10: try: downloaded = client.call('GET', f"/api/v1/attachments/{attachment['id']}/content", actor=bob) except Failure: sleep(0.1) continue actual = downloaded['headers']['X-Instance-Id'] check(actual != target, 'uploader still serves requests') check(downloaded['bytes'] == png and sha256(downloaded['bytes']).hexdigest() == attachment['sha256'], 'download failed checksum or byte comparison') print(f'PASS: upload on {target}; same bytes downloaded through {actual} after {monotonic() - start:.3f}s') return raise Failure('another replica did not return the original within 10 seconds') if __name__ == '__main__': run(main)