feat(lab5): implement reliable image pipeline and track 2
This commit is contained in:
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Destructive fault injection for a disposable, dedicated LAB5 Compose project."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
from image_probe import jpeg_size
|
||||
|
||||
COMPOSE = str(ROOT / 'scripts/compose.sh')
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run([COMPOSE, *args], check=True, text=True, capture_output=True, timeout=120).stdout.strip()
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-XAt', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'messenger', '-d', 'messenger', '-c', query)
|
||||
|
||||
|
||||
def job(attachment, version=1):
|
||||
return json.loads(sql(f"""SELECT row_to_json(j) FROM image_jobs j
|
||||
WHERE attachment_id='{attachment['id']}' AND pipeline_version={version}"""))
|
||||
|
||||
|
||||
def events(job_id, name):
|
||||
return int(sql(f"SELECT count(*) FROM job_events WHERE job_id='{job_id}' AND event='{name}'"))
|
||||
|
||||
|
||||
def operator(command, identifier, *args):
|
||||
return json.loads(compose('exec', '-T', 'recovery', 'python', '-m', 'src.operator', command,
|
||||
identifier, *args))
|
||||
|
||||
|
||||
def wait(predicate, description, timeout=105):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise AssertionError(f'timeout: {description}')
|
||||
|
||||
|
||||
def arm(attachment, point, action, version=1):
|
||||
sql(f"""INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action)
|
||||
VALUES ('{attachment['id']}',{version},'{point}','{action}')""")
|
||||
|
||||
|
||||
def hit(attachment, point, release=False):
|
||||
scope = f"attachment_id='{attachment['id']}' AND pipeline_version=1 AND point='{point}'"
|
||||
wait(lambda: sql(f'SELECT hit_at IS NOT NULL FROM pipeline_faults WHERE {scope}') == 't', point)
|
||||
if release:
|
||||
sql(f'UPDATE pipeline_faults SET released=true WHERE {scope}')
|
||||
|
||||
|
||||
def objects(attachment, version):
|
||||
prefix = f"results/{attachment['id']}/v{version}/"
|
||||
code = ("import json; from src.storage import s3,BUCKET; "
|
||||
f"print(json.dumps(sorted(x['Key'] for x in s3.list_objects_v2(Bucket=BUCKET,Prefix={prefix!r})"
|
||||
".get('Contents',[]))))")
|
||||
return json.loads(compose('exec', '-T', 'recovery', 'python', '-c', code))
|
||||
|
||||
|
||||
def report(name, started, attachment, **metrics):
|
||||
print(json.dumps(dict(scenario=name, result='PASS', seconds=round(time.monotonic() - started, 3),
|
||||
attachment_id=attachment['id'], **metrics), ensure_ascii=False), flush=True)
|
||||
|
||||
|
||||
def service_health(service):
|
||||
return [json.loads(line)['Health'] for line in
|
||||
compose('ps', '--format', 'json', service).splitlines()]
|
||||
|
||||
|
||||
def experiments(client):
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
worker_count = compose('ps', '-q', 'worker').splitlines()
|
||||
check(len(worker_count) >= 2, 'two workers are required')
|
||||
for service in ('publisher', 'worker'):
|
||||
enabled = compose('exec', '-T', service, 'printenv', 'PIPELINE_FAULTS')
|
||||
check(enabled == '1', f'fault injection disabled on {service}')
|
||||
|
||||
def upload():
|
||||
return client.attachment(alice, chat)
|
||||
|
||||
def meta(attachment, status=200):
|
||||
return client.call('GET', '/api/v1/attachments/' + attachment['id'], status,
|
||||
actor=bob, schema='Attachment')['json']
|
||||
|
||||
def verify(attachment, content, version=1):
|
||||
wait(lambda: job(attachment, version)['state'] == 'ready', f'job v{version} ready')
|
||||
ready = meta(attachment)
|
||||
check(ready['status'] == 'ready', 'attachment is not ready')
|
||||
row = job(attachment, version)
|
||||
active = int(sql(f"SELECT active_version FROM attachments WHERE id='{attachment['id']}'"))
|
||||
check(active == version, 'wrong active version')
|
||||
check(events(row['id'], 'published') == 1, 'expected one published manifest')
|
||||
check(set(row['manifest']) == {'original', 'thumbnail', 'crop', 'optimized'}, 'manifest incomplete')
|
||||
check(set(objects(attachment, version)) == {v['key'] for v in row['manifest'].values()},
|
||||
'unexpected keys or duplicated side effects')
|
||||
path = '/api/v1/attachments/' + attachment['id'] + '/content?variant='
|
||||
check({v['name'] for v in ready['variants']} == {'thumbnail', 'crop', 'optimized'}, 'wrong API variants')
|
||||
for variant, entry in row['manifest'].items():
|
||||
downloaded = client.call('GET', path + variant, actor=bob)
|
||||
data = downloaded['bytes']
|
||||
check(downloaded['headers'].get_content_type() == entry['content_type'], 'wrong MIME')
|
||||
check(len(data) == entry['size_bytes'], 'wrong size')
|
||||
check(hashlib.sha256(data).hexdigest() == entry['sha256'], 'wrong checksum')
|
||||
if variant == 'original':
|
||||
check(data == content, 'original changed')
|
||||
elif variant == 'optimized':
|
||||
check(data[:4] == b'RIFF' and data[8:12] == b'WEBP', 'invalid WebP signature')
|
||||
check((entry['width'], entry['height']) == (320, 200), 'WebP must not be enlarged')
|
||||
else:
|
||||
expected = (256, 160) if variant == 'thumbnail' else (128, 128)
|
||||
check(jpeg_size(data) == expected, 'wrong JPEG dimensions')
|
||||
return row
|
||||
|
||||
started = time.monotonic()
|
||||
key = 'concurrent-message-' + chat['id']
|
||||
def post_message(_):
|
||||
return client.message(alice, chat, 'concurrent', key=key)
|
||||
with ThreadPoolExecutor(max_workers=6) as executor:
|
||||
responses = list(executor.map(post_message, range(6)))
|
||||
check(len({response['json']['id'] for response in responses}) == 1, 'concurrent writes created duplicates')
|
||||
check(len({response['headers']['X-Instance-Id'] for response in responses}) >= 2,
|
||||
'concurrent requests did not reach two API instances')
|
||||
report('concurrent_message', started, {'id': None}, requests=6)
|
||||
|
||||
started = time.monotonic()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png'
|
||||
fixture = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
client.call('POST', path, 404, actor=eve, raw=fixture, headers={'Content-Type': 'image/png'})
|
||||
client.call('POST', path, 415, actor=alice, raw=fixture, headers={'Content-Type': 'image/jpeg'})
|
||||
client.call('POST', path, 415, actor=alice, raw=b'not a png', headers={'Content-Type': 'image/png'})
|
||||
client.call('POST', path, 413, actor=alice, raw=b'',
|
||||
headers={'Content-Type': 'image/png', 'Content-Length': '10485761'})
|
||||
report('upload_validation', started, {'id': None}, statuses=[404, 415, 415, 413])
|
||||
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'broker')
|
||||
try:
|
||||
attachment, content = upload()
|
||||
row = job(attachment)
|
||||
check(meta(attachment)['status'] == 'queued', 'upload did not remain queued')
|
||||
check(sql(f"SELECT count(*) FROM job_outbox WHERE job_id='{row['id']}'") == '1',
|
||||
'lost intent during real broker outage')
|
||||
wait(lambda: service_health('publisher') == ['unhealthy']
|
||||
and service_health('worker') == ['unhealthy'] * len(worker_count),
|
||||
'AMQP outage reflected in publisher and worker health', timeout=45)
|
||||
finally:
|
||||
compose('start', 'broker')
|
||||
verify(attachment, content)
|
||||
wait(lambda: service_health('publisher') == ['healthy']
|
||||
and service_health('worker') == ['healthy'] * len(worker_count),
|
||||
'publisher and all workers became healthy again', timeout=45)
|
||||
report('broker_unavailable', started, attachment, attempt=1, pipeline_health_recovered=True)
|
||||
|
||||
for point in ('before_publish', 'after_confirm', 'before_s3', 'after_s3', 'after_commit'):
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
if point in ('before_publish', 'after_confirm'):
|
||||
compose('stop', '-t', '1', 'worker')
|
||||
attachment, content = upload()
|
||||
arm(attachment, point, 'crash')
|
||||
compose('start', 'publisher')
|
||||
hit(attachment, point)
|
||||
if point in ('before_publish', 'after_confirm'):
|
||||
job_id = job(attachment)['id']
|
||||
wait(lambda: events(job_id, 'broker_confirmed'), 'outbox drained after publisher crash')
|
||||
compose('start', 'worker')
|
||||
if point in ('before_s3', 'after_s3'):
|
||||
keys = objects(attachment, 1)
|
||||
check(len(keys) == (0 if point == 'before_s3' else 4), 'wrong S3 effects at crash')
|
||||
check(job(attachment)['state'] == 'processing', 'manifest was already committed at crash')
|
||||
row = verify(attachment, content)
|
||||
wanted = {'before_s3': 2, 'after_s3': 2}.get(point, 1)
|
||||
check(row['attempt'] == wanted, f'wrong attempt after {point}')
|
||||
check(f'fault {point}: crash {row["id"]}' in compose('logs', '--no-color', 'publisher', 'worker'),
|
||||
'missing crash log')
|
||||
if point in ('after_commit', 'after_confirm'):
|
||||
wait(lambda: events(row['id'], 'delivery_ignored'), 'duplicate delivery ignored')
|
||||
report(point, started, attachment, attempt=row['attempt'], published=1)
|
||||
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
attachment, content = upload()
|
||||
arm(attachment, 'before_s3', 'pause')
|
||||
compose('start', 'publisher')
|
||||
hit(attachment, 'before_s3')
|
||||
initial = job(attachment)
|
||||
operator('redeliver', initial['id'])
|
||||
wait(lambda: events(initial['id'], 'delivery_ignored'), 'parallel duplicate rejected')
|
||||
check(events(initial['id'], 'claimed') == 1, 'duplicate obtained live lease')
|
||||
current = verify(attachment, content)
|
||||
check(current['fence'] > initial['fence'] and current['attempt'] == 2, 'lease was not reclaimed')
|
||||
hit(attachment, 'before_s3', release=True)
|
||||
wait(lambda: events(initial['id'], 'fence_rejected'), 'old attempt fenced')
|
||||
ignored = events(initial['id'], 'delivery_ignored')
|
||||
operator('redeliver', initial['id'])
|
||||
wait(lambda: events(initial['id'], 'delivery_ignored') > ignored, 'completed duplicate rejected')
|
||||
check(verify(attachment, content)['manifest'] == current['manifest'], 'duplicate changed the manifest')
|
||||
report('duplicate_and_fencing', started, attachment, fence=current['fence'], attempt=current['attempt'])
|
||||
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
attachment, content = upload()
|
||||
arm(attachment, 'after_s3', 'pause')
|
||||
compose('start', 'publisher')
|
||||
hit(attachment, 'after_s3')
|
||||
operator('reprocess', attachment['id'], '2')
|
||||
second = verify(attachment, content, 2)
|
||||
hit(attachment, 'after_s3', release=True)
|
||||
old = job(attachment)
|
||||
wait(lambda: job(attachment)['state'] == 'superseded' or events(old['id'], 'fence_rejected'),
|
||||
'v1 completed after v2 without publication')
|
||||
ignored = events(old['id'], 'delivery_ignored')
|
||||
operator('redeliver', old['id'])
|
||||
wait(lambda: events(old['id'], 'delivery_ignored') > ignored, 'reordered v1 redelivery ignored')
|
||||
check(verify(attachment, content, 2)['manifest'] == second['manifest'], 'v1 changed v2')
|
||||
check(events(old['id'], 'published') == 0, 'v1 published despite newer version')
|
||||
report('reorder_in_flight', started, attachment, active_version=2)
|
||||
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
attachment, content = upload()
|
||||
old = job(attachment)
|
||||
second = operator('reprocess', attachment['id'], '2')
|
||||
operator('redeliver', second['job_id'])
|
||||
verify(attachment, content, 2)
|
||||
check(job(attachment)['state'] == 'queued', 'v1 must still be queued before late delivery')
|
||||
operator('redeliver', old['id'])
|
||||
wait(lambda: events(old['id'], 'superseded') == 1, 'late v1 delivery superseded')
|
||||
check(events(old['id'], 'claimed') == 0, 'late v1 obtained a lease')
|
||||
compose('start', 'publisher')
|
||||
check(not objects(attachment, 1), 'late v1 produced S3 side effects')
|
||||
verify(attachment, content, 2)
|
||||
report('late_old_delivery', started, attachment, active_version=2)
|
||||
|
||||
started = time.monotonic()
|
||||
attachment, content = upload()
|
||||
first = verify(attachment, content)
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
try:
|
||||
operator('reprocess', attachment['id'], '2')
|
||||
check(meta(attachment)['status'] == 'ready', 'reprocessing hid the published version')
|
||||
visible = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content?variant=thumbnail',
|
||||
actor=bob)['bytes']
|
||||
check(hashlib.sha256(visible).hexdigest() == first['manifest']['thumbnail']['sha256'],
|
||||
'published version changed before v2 commit')
|
||||
finally:
|
||||
compose('start', 'publisher')
|
||||
second = verify(attachment, content, 2)
|
||||
for name in ('thumbnail', 'crop', 'optimized'):
|
||||
check(first['manifest'][name]['sha256'] != second['manifest'][name]['sha256'], 'v2 did not change bytes')
|
||||
operator('redeliver', first['id'])
|
||||
wait(lambda: events(first['id'], 'delivery_ignored'), 'duplicate of published v1')
|
||||
check(verify(attachment, content, 2)['manifest'] == second['manifest'], 'old duplicate changed v2')
|
||||
report('atomic_version_switch', started, attachment, active_version=2)
|
||||
|
||||
for action in ('temporary', 'permanent'):
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
attachment, content = upload()
|
||||
arm(attachment, 'before_s3', action)
|
||||
compose('start', 'publisher')
|
||||
initial = job(attachment)
|
||||
if action == 'permanent':
|
||||
wait(lambda: job(attachment)['state'] == 'failed', 'permanent failure')
|
||||
check(meta(attachment)['error_code'] == 'invalid_image', 'unsafe or wrong error code')
|
||||
path = '/api/v1/attachments/' + attachment['id'] + '/content'
|
||||
client.call('GET', path, 409, actor=bob)
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [attachment['id']]},
|
||||
headers={'Idempotency-Key': attachment['id']})
|
||||
check(sql(f"SELECT error_code FROM job_dead_letters WHERE job_id='{initial['id']}'") == 'invalid_image',
|
||||
'missing DLQ entry')
|
||||
operator('replay', initial['id'])
|
||||
check(sql(f"SELECT replayed_at IS NOT NULL FROM job_dead_letters WHERE job_id='{initial['id']}'") == 't',
|
||||
'missing replay audit')
|
||||
completed = verify(attachment, content)
|
||||
check(completed['attempt'] == 2, 'expected two attempts')
|
||||
if action == 'temporary':
|
||||
check(events(initial['id'], 'retry_scheduled') == 1, 'missing transient retry')
|
||||
report(action + '_error', started, attachment, attempt=2)
|
||||
|
||||
stable_attachment, stable_content = attachment, content
|
||||
stable_manifest = completed['manifest']
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'worker')
|
||||
attachment, content = upload()
|
||||
row = job(attachment)
|
||||
wait(lambda: events(row['id'], 'broker_confirmed'), 'durable queue entry')
|
||||
check(meta(attachment)['status'] == 'queued', 'worker processed despite stop')
|
||||
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=bob)
|
||||
message = client.message(alice, chat, '', attachments=[attachment['id']])['json']
|
||||
compose('restart', 'postgres', 'redis', 's3', 'broker', 'api', 'lb', 'publisher', 'recovery')
|
||||
wait(lambda: health(client), 'HAProxy readiness')
|
||||
check(not compose('ps', '-q', 'worker'), 'restart brought workers back too early')
|
||||
check(meta(attachment)['status'] == 'queued', 'confirmed job changed before worker restart')
|
||||
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=bob)
|
||||
compose('start', 'worker')
|
||||
verify(attachment, content)
|
||||
page = client.call('GET', f"/api/v1/chats/{chat['id']}/messages", actor=bob,
|
||||
schema='MessagePage')['json']
|
||||
check(any(item['id'] == message['id'] and attachment['id'] in item['attachment_ids']
|
||||
for item in page['items']), 'attachment link did not survive restart')
|
||||
wait(lambda: sql(f"SELECT staging_key IS NULL FROM attachments WHERE id='{attachment['id']}'") == 't',
|
||||
'recovery cleaned staging after publication')
|
||||
wait(lambda: service_health('recovery') == ['healthy'], 'recovery health after restart')
|
||||
check(verify(stable_attachment, stable_content)['manifest'] == stable_manifest,
|
||||
'published attachment changed on restart')
|
||||
check(job(attachment)['attempt'] == 1, 'broker restart lost the original delivery')
|
||||
report('restart_with_queued_attachment', started, attachment, attempt=1,
|
||||
message_link_preserved=True, staging_cleaned=True)
|
||||
|
||||
|
||||
def health(client):
|
||||
try:
|
||||
client.call('GET', '/health/ready')
|
||||
except (OSError, AssertionError):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--disposable', action='store_true', required=True,
|
||||
help='confirm this is an isolated test project')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
experiments(Client(args.base_url))
|
||||
except (AssertionError, OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
# Subprocess output can include internal details. Keep the public summary short.
|
||||
print('FAIL:', str(exc), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check image encoders, geometry, EXIF orientation and alpha on local fixtures."""
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURE = ROOT / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def render(directory, version):
|
||||
subprocess.run([sys.executable, '-m', 'src.render_image', str(directory), str(version)],
|
||||
cwd=ROOT, check=True)
|
||||
outputs = {}
|
||||
for variant, format_name in [('thumbnail', 'JPEG'), ('crop', 'JPEG'), ('optimized', 'WEBP')]:
|
||||
with Image.open(directory / variant) as image:
|
||||
image.load()
|
||||
assert image.format == format_name
|
||||
assert not image.getexif()
|
||||
outputs[variant] = (image.size, (directory / variant).read_bytes())
|
||||
return outputs
|
||||
|
||||
|
||||
def validate(path, mime):
|
||||
return subprocess.run([sys.executable, '-m', 'src.image_check', str(path), mime],
|
||||
cwd=ROOT, timeout=10, check=False).returncode
|
||||
|
||||
|
||||
def main():
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)
|
||||
original = directory / 'original'
|
||||
data = FIXTURE.read_bytes()
|
||||
original.write_bytes(data)
|
||||
assert validate(original, 'image/png') == 0
|
||||
assert validate(original, 'image/jpeg') == 15
|
||||
original.write_bytes(b'corrupt')
|
||||
assert validate(original, 'image/png') == 15
|
||||
# Rewrite only IHDR, with a valid CRC, to exercise the pre-decode limit.
|
||||
header = data[12:16] + struct.pack('>II', 10000, 10000) + data[24:29]
|
||||
original.write_bytes(data[:12] + header + struct.pack('>I', zlib.crc32(header)) + data[33:])
|
||||
assert validate(original, 'image/png') == 13
|
||||
original.write_bytes(data)
|
||||
print('PASS: PNG validation, MIME mismatch, corrupt input and pixel cap before decoding')
|
||||
first = render(directory, 1)
|
||||
assert first == render(directory, 1)
|
||||
second = render(directory, 2)
|
||||
assert first.keys() == second.keys()
|
||||
for variant, shape in [('thumbnail', (256, 160)), ('crop', (128, 128)), ('optimized', (320, 200))]:
|
||||
assert first[variant][0] == second[variant][0] == shape
|
||||
assert first[variant][1] != second[variant][1]
|
||||
assert original.read_bytes() == data
|
||||
print('PASS: fixture geometry, original preserved, deterministic v1, different v2')
|
||||
transparent = Image.new('RGBA', (7, 3), (255, 0, 0, 0))
|
||||
transparent.save(original, format='PNG')
|
||||
alpha = render(directory, 1)
|
||||
assert alpha['thumbnail'][0] == (7, 3)
|
||||
with Image.open(directory / 'thumbnail') as thumbnail:
|
||||
assert thumbnail.getpixel((0, 0)) == (255, 255, 255)
|
||||
rotated = Image.new('RGB', (17, 31), 'red')
|
||||
exif = rotated.getexif()
|
||||
exif[274] = 6
|
||||
rotated.save(original, format='JPEG', exif=exif)
|
||||
assert render(directory, 1)['thumbnail'][0] == (31, 17)
|
||||
print('PASS: alpha on white, no upscaling, EXIF orientation applied and metadata removed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user