ЛР5 БВТ2304 Запорожец на 5
RabbitMQ (quorum queue, publisher confirms, manual ack, DLX) + отдельный worker: staging в S3 + вложение/job/outbox одной транзакцией -> 202 queued; relay outbox, lease с heartbeat и fencing (worker_id, attempt), retry с backoff+jitter, failed-реестр, безопасный replay с audit; thumbnail/crop/WebP в изолированном процессе с лимитами. Тесты окон отказа (fault injection), трек 1 «Очередь под перегрузкой» с backpressure. Перенесено исправление замечания lab3 PR #99 (U+0000 в тексте). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Executable
+515
@@ -0,0 +1,515 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки lab5 (уровни 3–4). Запуск: sh scripts/test-lab5.sh (внутри сервиса tester).
|
||||
|
||||
Управляют стендом через docker (останавливают worker/S3/RabbitMQ, внедряют отказы файлами /tmp/fault-*),
|
||||
читают состояние из PostgreSQL и RabbitMQ, чтобы проверять не только HTTP-ответы, но и инварианты:
|
||||
нет второго набора вариантов, попытки ограничены, принятая работа не теряется.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
from image_probe import jpeg_size # noqa: E402
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
|
||||
PROJECT = 'mtusi-lab5'
|
||||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
JPEG = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
|
||||
|
||||
|
||||
# ---------- инфраструктура ----------
|
||||
|
||||
def docker(*args: str, stdin: str | None = None) -> str:
|
||||
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True, input=stdin).stdout.strip()
|
||||
|
||||
|
||||
def compose(*args: str) -> str:
|
||||
return subprocess.run(['docker', 'compose', '--env-file', str(ROOT / '.env'), *args], cwd=ROOT, check=True,
|
||||
text=True, capture_output=True).stdout.strip()
|
||||
|
||||
|
||||
def containers(service: str) -> list[str]:
|
||||
return docker('ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', f'label=com.docker.compose.service={service}').split()
|
||||
|
||||
|
||||
def sql(query: str) -> str:
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'app', '-d', 'messenger', '-tAc', query)
|
||||
|
||||
|
||||
def in_container(service: str, script: str) -> str:
|
||||
"""Python-скрипт внутри контейнера сервиса (там есть minio/aio-pika/Pillow и секреты).
|
||||
|
||||
Скрипт пишется в /tmp (tmpfs) и запускается файлом: multiprocessing forkserver не умеет стартовать
|
||||
из stdin. Код с побочными эффектами в скриптах — под if __name__ == '__main__'.
|
||||
"""
|
||||
return docker('exec', '-i', containers(service)[0], 'sh', '-c', 'cat > /tmp/_t.py && PYTHONPATH=/srv python /tmp/_t.py; rc=$?; rm -f /tmp/_t.py; exit $rc',
|
||||
stdin=script)
|
||||
|
||||
|
||||
def logs(container: str, since: str | None = None) -> str:
|
||||
"""docker logs: приложение пишет logging в stderr, поэтому склеиваем оба потока."""
|
||||
args = ['docker', 'logs'] + (['--since', since] if since else []) + [container]
|
||||
return subprocess.run(args, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout
|
||||
|
||||
|
||||
def start_worker() -> None:
|
||||
"""docker start, а не compose start: compose поднял бы и намеренно остановленные зависимости (S3)."""
|
||||
ids = docker('ps', '-aq', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', 'label=com.docker.compose.service=worker').split()
|
||||
docker('start', *ids)
|
||||
|
||||
|
||||
S3_PRELUDE = '''
|
||||
from minio import Minio
|
||||
import io
|
||||
k=open('/run/secrets/s3_access_key_id').read().strip(); s=open('/run/secrets/s3_secret_access_key').read().strip()
|
||||
m=Minio('s3:9000', access_key=k, secret_key=s, secure=False, region='us-east-1')
|
||||
B='messenger-attachments'
|
||||
def exists(key):
|
||||
try:
|
||||
m.stat_object(B, key); return True
|
||||
except Exception:
|
||||
return False
|
||||
'''
|
||||
|
||||
|
||||
def queue_counts() -> dict:
|
||||
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages')
|
||||
counts = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) == 2 and parts[1].isdigit():
|
||||
counts[parts[0]] = int(parts[1])
|
||||
return counts
|
||||
|
||||
|
||||
def wait_queue(name: str, minimum: int, seconds: float = 20) -> int:
|
||||
"""Счётчики list_queues у quorum queue обновляются периодически (метрики) — опрашиваем."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
n = queue_counts().get(name, 0)
|
||||
if n >= minimum or time.monotonic() > deadline:
|
||||
return n
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def wait_healthy(service: str, seconds: float = 90) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
ids = containers(service)
|
||||
if ids and all(docker('inspect', '-f', '{{.State.Health.Status}}', i) == 'healthy' for i in ids):
|
||||
return
|
||||
time.sleep(1)
|
||||
raise Failure(f'{service} did not become healthy')
|
||||
|
||||
|
||||
def wait_ready_api(c: Client, seconds: float = 90) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'API did not become ready')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def touch_fault(service: str, name: str) -> list[str]:
|
||||
ids = containers(service)
|
||||
for i in ids:
|
||||
docker('exec', '-u', '10001', i, 'touch', f'/tmp/fault-{name}')
|
||||
return ids
|
||||
|
||||
|
||||
def clear_fault(service: str, name: str) -> None:
|
||||
for i in containers(service):
|
||||
docker('exec', '-u', '10001', i, 'rm', '-f', f'/tmp/fault-{name}')
|
||||
|
||||
|
||||
# ---------- API ----------
|
||||
|
||||
def upload(c: Client, actor: dict, chat: dict, data: bytes = PNG, ctype: str = 'image/png') -> dict:
|
||||
att = c.call('POST', f"/api/v1/chats/{chat['id']}/attachments?filename=photo.png", 202, actor=actor, raw=data,
|
||||
headers={'Content-Type': ctype}, schema='Attachment')['json']
|
||||
check(att['status'] == 'queued' and att['variants'] == [] and att['error_code'] is None, 'bad queued snapshot')
|
||||
return att
|
||||
|
||||
|
||||
def meta(c: Client, actor: dict, att_id: str) -> dict:
|
||||
return c.call('GET', f'/api/v1/attachments/{att_id}', actor=actor, schema='Attachment')['json']
|
||||
|
||||
|
||||
def wait_status(c: Client, actor: dict, att_id: str, wanted: set, seconds: float = 90) -> dict:
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
m = meta(c, actor, att_id)
|
||||
if m['status'] in wanted:
|
||||
return m
|
||||
check(time.monotonic() < deadline, f'attachment stayed {m["status"]}, wanted {wanted}')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def content(c: Client, actor: dict, att_id: str, variant: str = 'original', expected=200) -> dict:
|
||||
return c.call('GET', f'/api/v1/attachments/{att_id}/content?variant={variant}', expected, actor=actor)
|
||||
|
||||
|
||||
def job(att_id: str) -> dict:
|
||||
row = sql(f"SELECT status, attempt, coalesce(error_code,''), "
|
||||
f"(SELECT count(*) FROM attachment_variants v WHERE v.attachment_id = j.attachment_id) "
|
||||
f"FROM attachment_jobs j WHERE attachment_id = '{att_id}'").split('|')
|
||||
return {'status': row[0], 'attempt': int(row[1]), 'error_code': row[2], 'variants': int(row[3])}
|
||||
|
||||
|
||||
def wait_published(att_id: str, seconds: float = 30) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while sql(f"SELECT count(*) FROM outbox o JOIN attachment_jobs j USING (job_id) "
|
||||
f"WHERE j.attachment_id = '{att_id}' AND o.published_at IS NULL") != '0':
|
||||
check(time.monotonic() < deadline, 'outbox row not published')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def webp_size(b: bytes) -> tuple[int, int]:
|
||||
check(b[:4] == b'RIFF' and b[8:12] == b'WEBP', 'not a WebP file')
|
||||
kind = b[12:16]
|
||||
if kind == b'VP8 ':
|
||||
return int.from_bytes(b[26:28], 'little') & 0x3fff, int.from_bytes(b[28:30], 'little') & 0x3fff
|
||||
if kind == b'VP8L':
|
||||
bits = int.from_bytes(b[21:25], 'little')
|
||||
return (bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1
|
||||
return int.from_bytes(b[24:27], 'little') + 1, int.from_bytes(b[27:30], 'little') + 1
|
||||
|
||||
|
||||
# ---------- уровень 3 ----------
|
||||
|
||||
def test_variants_contract(c: Client):
|
||||
"""Оригинал неизменен; thumbnail 256x160 JPEG, crop 128x128 JPEG, optimized WebP; checksums и реальные размеры."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat)
|
||||
ready = wait_status(c, bob, att['id'], {'ready'})
|
||||
check(ready['error_code'] is None, 'ready with error_code')
|
||||
variants = {v['name']: v for v in ready['variants']}
|
||||
check(sorted(variants) == ['crop', 'optimized', 'thumbnail'], f'variants: {sorted(variants)}')
|
||||
expect = {'thumbnail': ('image/jpeg', (256, 160)), 'crop': ('image/jpeg', (128, 128)),
|
||||
'optimized': ('image/webp', (320, 200))}
|
||||
for name, (ctype, size) in expect.items():
|
||||
v = variants[name]
|
||||
got = content(c, bob, att['id'], name)
|
||||
check(got['headers'].get_content_type() == ctype, f'{name}: content type')
|
||||
check(len(got['bytes']) == v['size_bytes'] and hashlib.sha256(got['bytes']).hexdigest() == v['sha256'],
|
||||
f'{name}: checksum')
|
||||
real = jpeg_size(got['bytes']) if ctype == 'image/jpeg' else webp_size(got['bytes'])
|
||||
check(real == size == (v['width'], v['height']), f'{name}: real size {real}, metadata {v["width"]}x{v["height"]}')
|
||||
original = content(c, bob, att['id'])
|
||||
check(original['bytes'] == PNG and original['headers'].get_content_type() == 'image/png', 'original changed')
|
||||
jpg = upload(c, alice, chat, JPEG, 'image/jpeg')
|
||||
r = wait_status(c, alice, jpg['id'], {'ready'})
|
||||
thumb = {v['name']: v for v in r['variants']}['thumbnail']
|
||||
check((thumb['width'], thumb['height']) == (160, 100), 'small image must not be upscaled')
|
||||
|
||||
|
||||
def test_worker_down_demo(c: Client):
|
||||
"""Сценарий защиты: worker остановлен -> 202 -> 409 -> сообщение создано -> рестарт API и RabbitMQ -> worker -> ready."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
att = upload(c, alice, chat)
|
||||
print(f' worker stopped; upload 202 attachment={att["id"]}')
|
||||
check(meta(c, bob, att['id'])['status'] == 'queued', 'must stay queued without worker')
|
||||
for variant in ('original', 'thumbnail'):
|
||||
content(c, bob, att['id'], variant, 409)
|
||||
msg = c.message(alice, chat, 'фото без worker', attachments=[att['id']])['json']
|
||||
check(msg['attachment_ids'] == [att['id']], 'message lost attachment')
|
||||
c.message(bob, chat, 'другие сообщения работают')
|
||||
wait_published(att['id'])
|
||||
before = wait_queue('attachment.process.v1', 1)
|
||||
check(before >= 1, 'job is not in the broker queue')
|
||||
compose('restart', 'api')
|
||||
wait_ready_api(c)
|
||||
compose('restart', 'rabbitmq')
|
||||
wait_healthy('rabbitmq')
|
||||
after = wait_queue('attachment.process.v1', 1)
|
||||
check(after >= 1, 'job lost on broker restart')
|
||||
print(f' api and rabbitmq restarted; queue depth before/after broker restart: {before}/{after}')
|
||||
check(meta(c, bob, att['id'])['status'] == 'queued', 'state changed without worker')
|
||||
finally:
|
||||
start_worker()
|
||||
started = time.monotonic()
|
||||
ready = wait_status(c, bob, att['id'], {'ready'}, 60)
|
||||
thumb = content(c, bob, att['id'], 'thumbnail')
|
||||
check(jpeg_size(thumb['bytes']) == (256, 160), 'thumbnail after restart is wrong')
|
||||
check(len(ready['variants']) == 3, 'variants missing')
|
||||
print(f' worker started -> ready in {time.monotonic() - started:.1f}s, thumbnail OK')
|
||||
|
||||
|
||||
def test_failed_state_and_409(c: Client):
|
||||
"""Постоянная ошибка (staging подменён в S3, sha256 не совпал) -> failed с безопасным кодом; 409 на content и attach."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
att = upload(c, alice, chat)
|
||||
in_container('api', S3_PRELUDE + f"m.put_object(B, 'staging/{att['id']}', io.BytesIO(b'garbage'), 7)\n")
|
||||
finally:
|
||||
start_worker()
|
||||
failed = wait_status(c, bob, att['id'], {'failed', 'ready'}, 60)
|
||||
check(failed['status'] == 'failed' and failed['error_code'] == 'source_corrupted', f'got {failed}')
|
||||
check(failed['variants'] == [], 'failed must have no variants')
|
||||
content(c, bob, att['id'], 'original', 409)
|
||||
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
j = job(att['id'])
|
||||
check(j['status'] == 'failed' and j['attempt'] == 1, f'permanent error must not be retried: {j}')
|
||||
|
||||
|
||||
def test_retry_bounded_then_replay(c: Client):
|
||||
"""Временная ошибка (S3 недоступен) -> ограниченные повторы с backoff -> failed retry_exhausted -> replay -> ready."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
s3 = containers('s3')[0]
|
||||
try:
|
||||
att = upload(c, alice, chat)
|
||||
docker('stop', s3)
|
||||
start_worker()
|
||||
started = time.monotonic()
|
||||
failed = wait_status(c, bob, att['id'], {'failed', 'ready'}, 150)
|
||||
check(failed['status'] == 'failed' and failed['error_code'] == 'retry_exhausted', f'got {failed}')
|
||||
max_attempts = int(sql("SELECT max_attempts FROM attachment_jobs WHERE attachment_id = '%s'" % att['id']))
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == max_attempts, f'attempts {j["attempt"]} != JOB_MAX_ATTEMPTS {max_attempts}')
|
||||
print(f' S3 down: failed retry_exhausted after {j["attempt"]} attempts, {time.monotonic() - started:.0f}s')
|
||||
worker_logs = logs(containers('worker')[0])
|
||||
job_id = att_job_id(att['id']) # один запрос, не на каждую строку лога
|
||||
delays = [line.split('retry in ')[1].split('s')[0] for line in worker_logs.splitlines()
|
||||
if job_id in line and 'retry in' in line]
|
||||
print(f' backoff delays (s): {", ".join(delays)}')
|
||||
check(len(delays) == max_attempts - 1, 'expected a retry delay per non-final attempt')
|
||||
finally:
|
||||
docker('start', s3)
|
||||
wait_healthy('s3')
|
||||
out = compose('exec', '-T', 'worker', 'python', '-m', 'app.replay', 'replay', '--attachment', att['id'],
|
||||
'--reason', 'S3 restored', '--dry-run')
|
||||
check('would replay' in out and meta(c, bob, att['id'])['status'] == 'failed', 'dry-run changed state')
|
||||
compose('exec', '-T', '-e', 'REPLAY_ACTOR=test', 'worker', 'python', '-m', 'app.replay', 'replay',
|
||||
'--attachment', att['id'], '--reason', 'S3 restored')
|
||||
ready = wait_status(c, bob, att['id'], {'ready'}, 60)
|
||||
check(len(ready['variants']) == 3, 'replay did not produce variants')
|
||||
out = compose('exec', '-T', 'worker', 'python', '-m', 'app.replay', 'replay', '--attachment', att['id'],
|
||||
'--reason', 'again')
|
||||
check('replay only for failed' in out, 'replay of a done job must be refused')
|
||||
audit = sql(f"SELECT count(*) FROM job_audit a JOIN attachment_jobs j USING (job_id) WHERE j.attachment_id = '{att['id']}'")
|
||||
check(audit == '1' and job(att['id'])['variants'] == 3, 'audit/variants after replay')
|
||||
|
||||
|
||||
def att_job_id(att_id: str) -> str:
|
||||
return sql(f"SELECT job_id FROM attachment_jobs WHERE attachment_id = '{att_id}'")
|
||||
|
||||
|
||||
def test_duplicate_delivery_is_noop(c: Client):
|
||||
"""Повторная доставка завершённой job: no-op + ack, без второго набора вариантов и без изменения updated_at."""
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat)
|
||||
ready = wait_status(c, alice, att['id'], {'ready'})
|
||||
job_id = att_job_id(att['id'])
|
||||
for _ in range(3):
|
||||
sql(f"INSERT INTO outbox (job_id, payload) SELECT job_id, payload FROM outbox WHERE job_id = '{job_id}' LIMIT 1")
|
||||
wait_published(att['id'])
|
||||
time.sleep(3)
|
||||
check(meta(c, alice, att['id'])['updated_at'] == ready['updated_at'], 'duplicate changed ready attachment')
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == 1 and j['variants'] == 3, f'duplicate created extra work: {j}')
|
||||
check(f'job {job_id}: no-op, already done' in logs(containers('worker')[0], '60s'), 'worker did not report no-op')
|
||||
|
||||
|
||||
# ---------- уровень 4 ----------
|
||||
|
||||
def test_crash_between_commit_and_publish(c: Client):
|
||||
"""API падает сразу после COMMIT (до 202 и publish): outbox восстанавливает намерение, файл доходит до ready."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
touch_fault('api', 'api_crash_after_commit')
|
||||
try:
|
||||
req = urllib.request.Request(f"{BASE_URL}/api/v1/chats/{chat['id']}/attachments?filename=crash.png", data=PNG,
|
||||
method='POST', headers={'Content-Type': 'image/png',
|
||||
'Authorization': 'Bearer ' + alice['token']})
|
||||
try:
|
||||
status = urllib.request.urlopen(req, timeout=30).status
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = exc.code
|
||||
except (urllib.error.URLError, OSError):
|
||||
status = 'connection error'
|
||||
check(status != 202, f'API should have crashed before 202, got {status}')
|
||||
print(f' client saw: {status} (API process exited after COMMIT)')
|
||||
finally:
|
||||
clear_fault('api', 'api_crash_after_commit')
|
||||
att_id = sql(f"SELECT id FROM attachments WHERE chat_id = '{chat['id']}'")
|
||||
check(len(att_id) == 36, 'attachment row must be committed')
|
||||
wait_ready_api(c)
|
||||
ready = wait_status(c, bob, att_id, {'ready'}, 60)
|
||||
check(len(ready['variants']) == 3, 'variants missing')
|
||||
print(f' attachment {att_id} reached ready via outbox relay')
|
||||
|
||||
|
||||
def test_worker_crash_after_s3_before_commit(c: Client):
|
||||
"""Worker умирает после записи объектов в S3, до COMMIT: аренда истекает, повтор даёт тот же результат."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
worker = touch_fault('worker', 'worker_crash_after_s3')[0]
|
||||
restarts = int(docker('inspect', '-f', '{{.RestartCount}}', worker))
|
||||
att = upload(c, alice, chat)
|
||||
started = time.monotonic()
|
||||
ready = wait_status(c, bob, att['id'], {'ready'}, 90)
|
||||
check(int(docker('inspect', '-f', '{{.RestartCount}}', worker)) == restarts + 1, 'worker did not crash')
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == 2 and j['variants'] == 3, f'expected second attempt with one variant set: {j}')
|
||||
keys = in_container('api', S3_PRELUDE + f"print(len(list(m.list_objects(B, prefix='variants/{att['id']}/', recursive=True))))\n")
|
||||
check(keys == '3', f'S3 has {keys} variant objects, expected 3 (same keys overwritten)')
|
||||
check(len(ready['variants']) == 3, 'variants missing')
|
||||
print(f' crash after S3 writes -> ready on attempt 2 in {time.monotonic() - started:.1f}s, 3 objects in S3')
|
||||
wait_healthy('worker')
|
||||
|
||||
|
||||
def test_worker_crash_after_commit_before_ack(c: Client):
|
||||
"""Worker умирает после COMMIT результата, до ack: redelivery видит done и подтверждает без повторной работы."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
worker = touch_fault('worker', 'worker_crash_after_commit')[0]
|
||||
att = upload(c, alice, chat)
|
||||
wait_status(c, bob, att['id'], {'ready'}, 60)
|
||||
wait_healthy('worker')
|
||||
job_id = att_job_id(att['id'])
|
||||
deadline = time.monotonic() + 30
|
||||
while f'job {job_id}: no-op, already done' not in logs(containers('worker')[0]):
|
||||
check(time.monotonic() < deadline, 'redelivered message was not acknowledged as no-op')
|
||||
time.sleep(1)
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == 1 and j['variants'] == 3, f'work was repeated: {j}')
|
||||
deadline = time.monotonic() + 20
|
||||
while queue_counts().get('attachment.process.v1', 0) != 0:
|
||||
check(time.monotonic() < deadline, 'message left in queue')
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def test_expired_lease_takeover(c: Client):
|
||||
"""Зависшая processing-задача (аренда истекла, владельца нет) перехватывается новой попыткой."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
att = upload(c, alice, chat)
|
||||
wait_published(att['id'])
|
||||
job_id = att_job_id(att['id'])
|
||||
sql(f"UPDATE attachment_jobs SET status='processing', attempt=1, worker_id='ghost-dead', "
|
||||
f"lease_until=clock_timestamp() - interval '1 second' WHERE job_id='{job_id}'")
|
||||
sql(f"UPDATE attachments SET status='processing' WHERE id='{att['id']}'")
|
||||
check(meta(c, bob, att['id'])['status'] == 'processing', 'processing state not visible in API')
|
||||
finally:
|
||||
start_worker()
|
||||
wait_status(c, bob, att['id'], {'ready'}, 60)
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == 2 and j['variants'] == 3, f'takeover result: {j}')
|
||||
|
||||
|
||||
def test_staging_cleanup_after_commit(c: Client):
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat)
|
||||
wait_status(c, alice, att['id'], {'ready'})
|
||||
out = in_container('api', S3_PRELUDE + f"print(exists('staging/{att['id']}'), exists('originals/{att['id']}'))\n")
|
||||
check(out == 'False True', f'staging/originals after ready: {out}')
|
||||
|
||||
|
||||
def test_poison_message_to_dlq(c: Client):
|
||||
before = queue_counts().get('attachment.process.v1.dlq', 0)
|
||||
in_container('api', '''
|
||||
import asyncio, aio_pika
|
||||
async def main():
|
||||
url = open('/run/secrets/broker_url').read().strip()
|
||||
conn = await aio_pika.connect(url)
|
||||
ch = await conn.channel(publisher_confirms=True)
|
||||
ex = await ch.get_exchange('attachments')
|
||||
await ex.publish(aio_pika.Message(b'{"not":"a job"}', delivery_mode=2), routing_key='attachment.process.v1')
|
||||
await conn.close()
|
||||
asyncio.run(main())
|
||||
''')
|
||||
deadline = time.monotonic() + 15
|
||||
while queue_counts().get('attachment.process.v1.dlq', 0) != before + 1:
|
||||
check(time.monotonic() < deadline, 'invalid message did not reach DLQ')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def test_prefetch_limited(c: Client):
|
||||
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_consumers', 'queue_name', 'prefetch_count')
|
||||
rows = [l.split() for l in out.splitlines() if l.startswith('attachment.process.v1')]
|
||||
expected = os.environ.get('WORKER_PREFETCH_EXPECTED', '2')
|
||||
check(rows and all(r[1] == expected for r in rows), f'consumers/prefetch: {rows}')
|
||||
|
||||
|
||||
def test_worker_resource_limits(c: Client):
|
||||
"""Лимиты worker: бомба памяти -> resource_limit (permanent), долгая обработка -> timeout (transient)."""
|
||||
out = in_container('worker', '''
|
||||
import asyncio, io, struct, zlib
|
||||
from PIL import Image
|
||||
from app import imaging
|
||||
def ch(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d) & 0xffffffff)
|
||||
async def main():
|
||||
w = h = 6000 # 36 Мпикс: проходит лимит пикселей, но RGB-декодирование ~108 MiB
|
||||
raw = zlib.compress(b''.join(b'\\0' + b'\\0' * (3 * w) for _ in range(h)), 1)
|
||||
big = b'\\x89PNG\\r\\n\\x1a\\n' + ch(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)) + ch(b'IDAT', raw) + ch(b'IEND', b'')
|
||||
try:
|
||||
await imaging.run_isolated(big, 40_000_000, 96, 60); print('mem: no error')
|
||||
except imaging.PermanentImageError as e:
|
||||
print('mem:', e.code)
|
||||
try:
|
||||
await imaging.run_isolated(big, 40_000_000, 1024, 0.2); print('time: no error')
|
||||
except imaging.TransientImageError as e:
|
||||
print('time:', e.code)
|
||||
rgba = Image.new('RGBA', (300, 200), (255, 0, 0, 0)); b = io.BytesIO(); rgba.save(b, 'PNG')
|
||||
v = await imaging.run_isolated(b.getvalue(), 40_000_000, 512, 30)
|
||||
print('alpha:', Image.open(io.BytesIO(v[0]['data'])).convert('RGB').getpixel((10, 10)))
|
||||
im = Image.new('RGB', (300, 100)); ex = im.getexif(); ex[0x0112] = 6; b = io.BytesIO(); im.save(b, 'JPEG', exif=ex)
|
||||
v = await imaging.run_isolated(b.getvalue(), 40_000_000, 512, 30)
|
||||
t = Image.open(io.BytesIO(v[0]['data']))
|
||||
print('exif:', t.size, t.getexif().get(0x0112))
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
''')
|
||||
print(' ' + out.replace('\n', '; '))
|
||||
check('mem: resource_limit' in out, 'memory limit not enforced')
|
||||
check('time: processing_timeout' in out, 'timeout not enforced')
|
||||
alpha = out.split('alpha: (')[1].split(')')[0].split(', ')
|
||||
check(all(int(x) >= 250 for x in alpha), 'alpha not composited on white')
|
||||
check('exif: (85, 256) None' in out, 'EXIF orientation not applied or metadata not stripped')
|
||||
|
||||
|
||||
TESTS = [test_variants_contract, test_worker_down_demo, test_failed_state_and_409, test_duplicate_delivery_is_noop,
|
||||
test_retry_bounded_then_replay, test_crash_between_commit_and_publish,
|
||||
test_worker_crash_after_s3_before_commit, test_worker_crash_after_commit_before_ack,
|
||||
test_expired_lease_takeover, test_staging_cleanup_after_commit, test_poison_message_to_dlq,
|
||||
test_prefetch_limited, test_worker_resource_limits]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = Client(BASE_URL, timeout=30)
|
||||
wait_ready_api(c)
|
||||
only = set(sys.argv[1:])
|
||||
failed = 0
|
||||
selected = [t for t in TESTS if not only or t.__name__ in only]
|
||||
for test in selected:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
test(c)
|
||||
print(f'PASS {test.__name__} ({time.monotonic() - started:.1f}s)', flush=True)
|
||||
except (Failure, subprocess.CalledProcessError, OSError) as exc:
|
||||
failed += 1
|
||||
detail = getattr(exc, 'stderr', '') or ''
|
||||
print(f'FAIL {test.__name__}: {exc} {detail.strip()[-300:]}', flush=True)
|
||||
print(f'{len(selected) - failed}/{len(selected)} passed')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user