test(attachments): verify crash recovery and queue overload

This commit is contained in:
2026-11-26 18:56:01 +03:00
parent f0fc096948
commit 3c5ddf382b
7 changed files with 880 additions and 1 deletions
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""Crash the API in an isolated Compose project after outbox COMMIT."""
import json
import re
import subprocess
import tempfile
import time
import urllib.request
import uuid
from pathlib import Path
from client import Client, Failure, NoRedirect, ROOT, check, run
TOPIC = 'attachments.process.v1'
GATE = '/tmp/lab5-outbox-crash-release'
PRELOAD = '/app/outbox-crash.cjs'
def docker(*args, timeout=60, show_output=False, include_stderr=False):
try:
result = subprocess.run(
['docker', *args], cwd=ROOT, text=True, encoding='utf-8',
errors='replace', capture_output=not show_output, timeout=timeout,
)
except subprocess.TimeoutExpired:
raise Failure(f'Docker command timed out after {timeout} seconds') from None
if result.returncode:
raise Failure(f'Docker command failed with exit code {result.returncode}: {args[0]}')
output = result.stdout or ''
if include_stderr:
output += result.stderr or ''
return output.strip()
def api_client(compose):
binding = compose('port', 'api', '8080')
check(re.fullmatch(r'127\.0\.0\.1:[0-9]+', binding), 'expected a loopback API port')
client = Client('http://' + binding, timeout=30)
client.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
return client
def snapshot(compose, attachment_id):
query = (
'SELECT a.status, a.published_at IS NOT NULL, a.generation, '
'(SELECT count(*) FROM attachment_outbox AS o WHERE o.attachment_id = a.id) '
f"FROM attachments AS a WHERE a.id = '{attachment_id}'::uuid"
)
return compose(
'exec', '-T', 'postgres', 'sh', '-c',
'exec psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "$1"',
'sh', query,
)
def topic_offset(compose):
output = compose(
'exec', '-T', 'kafka', '/opt/kafka/bin/kafka-get-offsets.sh',
'--bootstrap-server', 'kafka:9092', '--topic', TOPIC, timeout=90,
)
offsets = re.findall(r'^' + re.escape(TOPIC) + r':0:([0-9]+)$', output, re.MULTILINE)
check(len(offsets) == 1, 'expected the Kafka attachment topic offset')
return int(offsets[0])
def main():
project = 'lab5-outbox-crash-' + uuid.uuid4().hex[:12]
with tempfile.TemporaryDirectory(prefix=project + '-') as directory:
overlay = Path(directory) / 'compose.json'
api = {
'deploy': {'replicas': 1},
'restart': 'no',
'ports': [{'host_ip': '127.0.0.1', 'target': 8080, 'published': '0'}],
'healthcheck': {'start_period': '120s'},
}
instrumented = dict(
api,
environment={'NODE_OPTIONS': '--require=' + PRELOAD},
volumes=[{
'type': 'bind', 'source': str(ROOT / 'tests/outbox-crash.cjs'),
'target': PRELOAD, 'read_only': True,
}],
)
def configure(api_config):
overlay.write_text(json.dumps({'services': {'api': api_config}}), encoding='utf-8')
def compose(*args, **options):
return docker(
'compose', '-p', project, '-f', str(ROOT / 'compose.yaml'), '-f',
str(overlay), *args, **options,
)
configure(instrumented)
try:
print('Starting isolated Compose test: ' + project, flush=True)
compose('up', '-d', '--build', '--wait', '--wait-timeout', '240',
'api', timeout=900, show_output=True)
compose('up', '-d', '--build', '--no-deps', 'worker',
timeout=900, show_output=True)
client = api_client(compose)
alice, bob, _, chat = client.bootstrap()
accepted, original = client.attachment(alice, chat)
attachment_id = str(uuid.UUID(accepted['id']))
check(snapshot(compose, attachment_id) == 'queued|f|0|1', 'upload was not committed to outbox')
before = topic_offset(compose)
check(before == 0, 'the attachment topic is not empty before injection')
container = compose('ps', '-q', 'api')
check(re.fullmatch(r'[0-9a-f]{12,64}', container), 'expected a single API container')
compose('exec', '-T', 'api', 'touch', GATE)
check(docker('container', 'wait', container, timeout=90) == '86', 'expected injected API exit code 86')
logs = docker('container', 'logs', container, include_stderr=True)
marker = {'event': 'outbox_crash_before_publish', 'attachmentIds': [attachment_id]}
check(json.dumps(marker, separators=(',', ':')) in logs, 'wrong attachment in injected crash')
check(snapshot(compose, attachment_id) == 'queued|f|0|1', 'outbox job changed during the crash')
check(topic_offset(compose) == before, 'Kafka received a record before the API crashed')
print('PASS: committed upload survived injected exit before Kafka publish', flush=True)
configure(api)
compose('up', '-d', '--no-deps', '--no-build', '--force-recreate', '--wait',
'--wait-timeout', '180', 'api', timeout=240, show_output=True)
recovered = api_client(compose)
ready = recovered.wait_ready(bob, accepted, wait_seconds=120)
check(ready['id'] == attachment_id and ready['sha256'] == accepted['sha256'],
'recovery returned a different attachment')
content = recovered.call('GET', '/api/v1/attachments/' + attachment_id + '/content', actor=bob)
check(content['bytes'] == original, 'original bytes changed after recovery')
deadline = time.monotonic() + 30
while snapshot(compose, attachment_id) != 'ready|t|0|0':
check(time.monotonic() < deadline, 'publisher did not clear the outbox after Kafka confirmation')
time.sleep(0.5)
print('PASS: the same attachment reached ready through outbox after restarting API')
finally:
compose('down', '--volumes', '--timeout', '5', timeout=150, show_output=True)
if __name__ == '__main__':
run(main)