Files
mtusi2026lab5/student-tests/attachment_failover.py
T
Vladislav Kunetskiy 01b885e846 lab5: очереди и асинхронная обработка изображений
Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
2026-10-31 14:34:24 +03:00

82 lines
2.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""Upload through one API replica, stop it, download through another.
Run against a live stand:
python3 student-tests/attachment_failover.py --base-url http://localhost:8080
"""
import hashlib
import os
import subprocess
import sys
import time
from pathlib import Path
from urllib.parse import quote
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from client import Client, Failure, arguments, check, run # noqa: E402
from tests_helpers import ROOT, compose # noqa: E402
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
def main():
args = arguments('Attachment failover across API replicas (lab4)')
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
content = FIXTURE.read_bytes()
response = client.call(
'POST',
'/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote('failover.png'),
202,
actor=alice,
raw=content,
headers={'Content-Type': 'image/png'},
schema='Attachment',
)
attachment = response['json']
instance = response['headers'].get('X-Instance-Id')
check(bool(instance), 'upload response has no X-Instance-Id')
check(attachment['sha256'] == hashlib.sha256(content).hexdigest(), 'upload checksum mismatch')
attachment = client.wait_ready(alice, attachment)
stop = subprocess.run(
[str(ROOT / 'scripts/stop-one.sh')],
cwd=ROOT,
env={**os.environ, 'TARGET_INSTANCE_ID': instance},
capture_output=True,
text=True,
)
check(stop.returncode == 0, 'stop-one.sh failed: ' + stop.stderr.strip())
deadline = time.monotonic() + 30
last_error = None
while time.monotonic() < deadline:
try:
download = client.call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob,
)
if download['bytes'] == content:
metadata = client.call(
'GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment',
)['json']
check(metadata['sha256'] == attachment['sha256'], 'metadata changed after failover')
print('PASS: lab4 attachment failover; served by', instance)
return
last_error = 'downloaded bytes differ from the original'
except Failure as error:
last_error = str(error)
time.sleep(1)
raise Failure('download did not recover within 30s: ' + str(last_error))
if __name__ == '__main__':
try:
run(main)
finally:
compose('up', '-d', '--no-deps', 'api', check=False)