#!/usr/bin/env python3 """Reproducible level-4 checks against the compose stack. Prints attachment ids, statuses and variant counts. Does not print tokens, passwords or broker URLs. Track 5 is not part of this script. """ import base64 import json import secrets import shlex import subprocess import time import urllib.error import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] BASE = 'http://127.0.0.1:8080' FIXTURE = ROOT / 'tests' / 'fixtures' / 'sample.png' UUID = __import__('re').compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') class DemoError(Exception): pass def run(args, check=True): completed = subprocess.run( args, cwd=str(ROOT), capture_output=True, text=True, check=False, ) if check and completed.returncode != 0: detail = (completed.stderr or completed.stdout or '').strip().splitlines() tail = detail[-1] if detail else 'exit %s' % completed.returncode raise DemoError(args[0] + ' failed: ' + tail[:200]) return completed def compose(*args, check=True): return run(['docker', 'compose', '--env-file', '.env', *args], check=check) def fault(*args): last = None for _ in range(20): last = compose('exec', '-T', 'api', 'python', '-m', 'app.fault', *args, check=False) if last.returncode == 0: return last.stdout.strip() time.sleep(1) raise DemoError('fault %s failed' % ' '.join(args)) def psql(sql): script = 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tA -c %s' % shlex.quote(sql) last = None for _ in range(10): last = compose('exec', '-T', 'postgres', 'sh', '-c', script, check=False) if last.returncode == 0: return last.stdout.strip() time.sleep(1) raise DemoError('psql failed') def replay(attachment_id): if UUID.fullmatch(attachment_id) is None: raise DemoError('replay id is not a uuid') text = None for _ in range(20): completed = compose('exec', '-T', 'api', 'python', '-m', 'app.replay', attachment_id, check=False) if completed.returncode == 0: text = completed.stdout.strip() break time.sleep(1) if text is None: raise DemoError('replay did not run') print('replay %s' % text) return text def restart_counts(): listed = compose('ps', '-a', '-q', 'api') counts = {} for container_id in listed.stdout.split(): inspected = run(['docker', 'inspect', '-f', '{{.RestartCount}}', container_id]) counts[container_id[:12]] = int(inspected.stdout.strip() or '0') return counts def request(method, path, token=None, body=None, raw=None, content_type=None, accept=None): data = raw headers = {} if body is not None: data = json.dumps(body).encode('utf-8') headers['Content-Type'] = 'application/json' if content_type: headers['Content-Type'] = content_type if token: headers['Authorization'] = 'Bearer ' + token req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=30) as response: payload = response.read() code = response.status except urllib.error.HTTPError as exc: payload = exc.read() code = exc.code except urllib.error.URLError as exc: reason = exc.reason raise DemoError('%s %s connection failed (%s)' % (method, path, type(reason).__name__)) from None except OSError as exc: raise DemoError('%s %s connection failed (%s)' % (method, path, type(exc).__name__)) from None if accept is not None and code not in accept: raise DemoError('%s %s -> %s' % (method, path.split('?')[0], code)) return code, payload def json_body(payload): return json.loads(payload.decode('utf-8')) def wait_ready_http(): deadline = time.monotonic() + 90 while time.monotonic() < deadline: try: code, _payload = request('GET', '/health/ready', accept=(200, 503)) except DemoError: time.sleep(1) continue if code == 200: return time.sleep(1) raise DemoError('API did not become ready') def session(): username = 'u' + secrets.token_hex(4) password = secrets.token_urlsafe(18) code, payload = request( 'POST', '/api/v1/users', body={'username': username, 'display_name': 'Демо', 'password': password}, accept=(201,), ) user = json_body(payload) basic = base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii') req = urllib.request.Request( BASE + '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + basic}, method='POST', ) try: with urllib.request.urlopen(req, timeout=30) as response: opened = json.loads(response.read().decode('utf-8')) except urllib.error.HTTPError as exc: raise DemoError('login -> %s' % exc.code) from None token = opened['token'] code, payload = request( 'POST', '/api/v1/chats', token=token, body={'title': 'Уровень 4', 'member_ids': [user['id']]}, accept=(201,), ) chat = json_body(payload) return token, chat['id'] def upload(token, chat_id): """Return (status, attachment id). status 0 means the connection died. The token is not logged.""" try: code, payload = request( 'POST', '/api/v1/chats/%s/attachments?filename=sample.png' % chat_id, token=token, raw=FIXTURE.read_bytes(), content_type='image/png', accept=(202, 500, 502, 503, 504), ) except DemoError: return 0, None if code != 202: return code, None return 202, json_body(payload)['id'] def meta(token, attachment_id): deadline = time.monotonic() + 30 while True: try: code, payload = request( 'GET', '/api/v1/attachments/' + attachment_id, token=token, accept=(200, 503), ) except DemoError: if time.monotonic() > deadline: raise time.sleep(0.5) continue if code == 200: return json_body(payload) if time.monotonic() > deadline: raise DemoError('metadata unavailable') time.sleep(0.5) def wait_status(token, attachment_id, wanted, seconds=60): deadline = time.monotonic() + seconds last = None while time.monotonic() < deadline: last = meta(token, attachment_id) if last['status'] == wanted: return last if wanted != 'failed' and last['status'] == 'failed': raise DemoError('%s failed with %s' % (attachment_id, last.get('error_code'))) time.sleep(0.4) raise DemoError('%s stayed %s' % (attachment_id, last['status'] if last else 'unknown')) def published_at(attachment_id): if UUID.fullmatch(attachment_id) is None: raise DemoError('id is not a uuid') return psql( "SELECT COALESCE(published_at::text, 'null') FROM attachment_jobs WHERE attachment_id = '%s'" % attachment_id ) def variant_count(attachment_id): if UUID.fullmatch(attachment_id) is None: raise DemoError('id is not a uuid') return int(psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % attachment_id)) def jpeg_size(data): if data[:2] != b'\xff\xd8': raise DemoError('not a jpeg') index = 2 sof = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} while index < len(data): if data[index] != 0xFF: raise DemoError('bad jpeg') while index < len(data) and data[index] == 0xFF: index += 1 marker = data[index] index += 1 if marker in (0xD8, 0xD9, 0xDA) or 0xD0 <= marker <= 0xD7: if marker in (0xD9, 0xDA): break continue if index + 2 > len(data): raise DemoError('short jpeg') length = int.from_bytes(data[index:index + 2], 'big') if marker in sof: height = int.from_bytes(data[index + 3:index + 5], 'big') width = int.from_bytes(data[index + 5:index + 7], 'big') return width, height index += length raise DemoError('jpeg size missing') def download(token, attachment_id, variant): code, payload = request( 'GET', '/api/v1/attachments/%s/content?variant=%s' % (attachment_id, variant), token=token, accept=(200,), ) return code, payload def assert_ready_variants(token, attachment_id): ready = wait_status(token, attachment_id, 'ready') names = {} for item in ready['variants']: names[item['name']] = item if set(names) != {'thumbnail', 'crop', 'optimized'}: raise DemoError('variants %s' % sorted(names)) if (names['thumbnail']['width'], names['thumbnail']['height']) != (256, 160): raise DemoError('thumbnail metadata') if (names['crop']['width'], names['crop']['height']) != (128, 128): raise DemoError('crop metadata') if names['optimized']['content_type'] != 'image/webp': raise DemoError('optimized type') if (names['optimized']['width'], names['optimized']['height']) != (320, 200): raise DemoError('optimized metadata') _code, thumb = download(token, attachment_id, 'thumbnail') if jpeg_size(thumb) != (256, 160): raise DemoError('thumbnail bytes') _code, crop = download(token, attachment_id, 'crop') if jpeg_size(crop) != (128, 128): raise DemoError('crop bytes') _code, optimized = download(token, attachment_id, 'optimized') if optimized[:4] != b'RIFF' or optimized[8:12] != b'WEBP': raise DemoError('optimized bytes') if variant_count(attachment_id) != 3: raise DemoError('variant rows %s' % variant_count(attachment_id)) deadline = time.monotonic() + 15 while time.monotonic() < deadline: cleared = psql( "SELECT (staging_key = object_key) FROM attachments WHERE id = '%s'" % attachment_id ) if cleared == 't': break time.sleep(0.4) else: raise DemoError('staging was kept after ready') return ready def attachment_ids(): found = psql('SELECT id FROM attachments') return {item for item in found.splitlines() if UUID.fullmatch(item)} def pause_gap(token, chat_id, label): before = attachment_ids() before_restarts = restart_counts() fault('arm', 'pause-outbox') crash = label == 'commit-before-publish' if crash: fault('arm', 'commit-before-publish') status, uploaded = upload(token, chat_id) if not crash and status != 202: raise DemoError('pause-outbox upload -> %s' % status) if crash: deadline = time.monotonic() + 30 while time.monotonic() < deadline: after = restart_counts() if sum(after.values()) > sum(before_restarts.values()): break time.sleep(1) else: raise DemoError('commit-before-publish did not restart an API replica') created = sorted(attachment_ids() - before) if uploaded and uploaded not in created: created.append(uploaded) if not created: raise DemoError('%s created no attachment' % label) attachment_id = uploaded or created[-1] time.sleep(2) stamp = published_at(attachment_id) if stamp != 'null': raise DemoError('%s published_at=%s while outbox is paused' % (label, stamp)) if meta(token, attachment_id)['status'] == 'ready': raise DemoError('%s became ready while outbox is paused' % label) fault('clear') assert_ready_variants(token, attachment_id) print('%s attachment=%s published_at_while_paused=null status_after=ready variants=3' % (label, attachment_id)) def lease_reclaim(token, chat_id): """A processing row with an expired lease and no live lock is queued again, then finishes.""" fault('arm', 'pause-outbox') status, attachment_id = upload(token, chat_id) if status != 202 or UUID.fullmatch(attachment_id or '') is None: raise DemoError('lease upload -> %s' % status) psql( "UPDATE attachments SET status = 'processing' WHERE id = '%s' AND status = 'queued'" % attachment_id ) psql( "UPDATE attachment_jobs SET lease_until = clock_timestamp() - interval '1 minute', " "published_at = clock_timestamp() WHERE attachment_id = '%s'" % attachment_id ) deadline = time.monotonic() + 20 while time.monotonic() < deadline: if meta(token, attachment_id)['status'] == 'queued' and published_at(attachment_id) == 'null': break time.sleep(0.4) else: raise DemoError('expired lease was not reclaimed') fault('clear') assert_ready_variants(token, attachment_id) print('lease-expired attachment=%s reclaimed=queued status_after=ready variants=3' % attachment_id) def worker_crash(token, chat_id): fault('arm', 'exit-after-put') status, attachment_id = upload(token, chat_id) if status != 202 or not attachment_id: raise DemoError('exit-after-put upload -> %s' % status) assert_ready_variants(token, attachment_id) print('exit-after-put attachment=%s variants=3 same_result=yes' % attachment_id) def permanent_and_replay(token, chat_id): fault('arm', 'permanent-once') status, attachment_id = upload(token, chat_id) if status != 202 or not attachment_id: raise DemoError('permanent-once upload -> %s' % status) failed = wait_status(token, attachment_id, 'failed') if failed['error_code'] != 'invalid_image': raise DemoError('error_code %s' % failed.get('error_code')) rows = psql( "SELECT error_code FROM attachment_job_failures f JOIN attachment_jobs j ON j.id = f.job_id " "WHERE j.attachment_id = '%s'" % attachment_id ) if 'invalid_image' not in rows.splitlines(): raise DemoError('failure registry missed invalid_image') queues = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', 'list_queues', 'name', 'messages') dlq = '0' for line in queues.stdout.splitlines(): parts = line.split() if len(parts) == 2 and parts[0] == 'attachment.jobs.dlq': dlq = parts[1] if dlq == '0': raise DemoError('DLQ is empty') first = replay(attachment_id) if not first.startswith('requeued '): raise DemoError('first replay was %s' % first.split()[0]) assert_ready_variants(token, attachment_id) second = replay(attachment_id) if not second.startswith('already_ready '): raise DemoError('second replay was %s' % second.split()[0]) if variant_count(attachment_id) != 3: raise DemoError('replay duplicated variants') print('permanent-once attachment=%s failed=invalid_image dlq=%s replay=requeued second=already_ready variants=3' % (attachment_id, dlq)) def transient(token, chat_id): fault('arm', 'transient-once') status, attachment_id = upload(token, chat_id) if status != 202 or not attachment_id: raise DemoError('transient-once upload -> %s' % status) assert_ready_variants(token, attachment_id) logs = compose('logs', '--since', '3m', 'worker', check=False) text = logs.stdout + '\n' + logs.stderr logged = any('will retry in ' in line and attachment_id in line for line in text.splitlines()) if not logged: raise DemoError('backoff line was not logged') print('transient-once attachment=%s backoff=logged variants=3' % attachment_id) def main(): wait_ready_http() fault('clear') token, chat_id = session() try: pause_gap(token, chat_id, 'pause-outbox') pause_gap(token, chat_id, 'commit-before-publish') lease_reclaim(token, chat_id) worker_crash(token, chat_id) permanent_and_replay(token, chat_id) transient(token, chat_id) finally: try: fault('clear') except DemoError as exc: print(exc) print('PASS: level 4 outbox, crash, lease redelivery, DLQ replay, backoff') if __name__ == '__main__': try: main() except DemoError as exc: print('FAIL:', exc) raise SystemExit(1)