forked from mtusi2026/mtusi2026lab5
Implement lab5 async image processing with RabbitMQ and outbox
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Concurrent Lab5 uploads (HTTP 202) and eventual processing completion.
|
||||
|
||||
Admission metrics measure upload/enqueue requests, not worker throughput.
|
||||
Completion is checked separately so an accepted-but-stuck job cannot pass.
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import json
|
||||
import statistics
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--concurrency', type=int, default=10)
|
||||
parser.add_argument('--output', default='evidence/attachments-concurrent.json')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--wait-seconds', type=int, default=180)
|
||||
args = parser.parse_args()
|
||||
check(args.concurrency > 0, 'concurrency must be positive')
|
||||
check(args.wait_seconds > 0, 'wait-seconds must be positive')
|
||||
|
||||
client = Client(args.base_url)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
source = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=parallel.png'
|
||||
|
||||
def upload(_):
|
||||
cli = Client(args.base_url)
|
||||
response = cli.call('POST', path, 202, actor=alice, raw=source,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
att = response['json']
|
||||
check(att['status'] == 'queued', '202 must return a queued attachment')
|
||||
check(att['size_bytes'] == len(source), 'size mismatch')
|
||||
check(att['chat_id'] == chat['id'] and att['owner_id'] == alice['id'],
|
||||
'incorrect attachment ownership')
|
||||
return att['id'], response['elapsed']
|
||||
|
||||
started = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
results = list(pool.map(upload, range(args.concurrency)))
|
||||
accepted_seconds = time.monotonic() - started
|
||||
ids = [att_id for att_id, _ in results]
|
||||
timings = [duration for _, duration in results]
|
||||
check(len(set(ids)) == args.concurrency, 'duplicate attachment IDs')
|
||||
|
||||
# A 202 response alone only proves acceptance, not successful processing.
|
||||
pending = set(ids)
|
||||
deadline = time.monotonic() + args.wait_seconds
|
||||
while pending and time.monotonic() < deadline:
|
||||
for att_id in list(pending):
|
||||
att = client.call('GET', '/api/v1/attachments/' + att_id,
|
||||
actor=alice, schema='Attachment')['json']
|
||||
check(att['status'] != 'failed', 'attachment reached failed: ' + att_id)
|
||||
if att['status'] == 'ready':
|
||||
variants = [v['name'] for v in att['variants']]
|
||||
check(len(variants) == 3 and set(variants) == {'thumbnail', 'crop', 'optimized'},
|
||||
'missing/duplicate image variants: ' + att_id)
|
||||
pending.remove(att_id)
|
||||
if pending:
|
||||
time.sleep(0.5)
|
||||
check(not pending, 'attachments not ready before deadline: ' + str(len(pending)))
|
||||
complete_seconds = time.monotonic() - started
|
||||
|
||||
data = {
|
||||
'concurrency': args.concurrency,
|
||||
'accepted_uploads': len(results),
|
||||
'ready_attachments': args.concurrency,
|
||||
'failed_requests': 0,
|
||||
'acceptance_elapsed_seconds': round(accepted_seconds, 3),
|
||||
'acceptance_rps': round(len(results) / accepted_seconds, 3),
|
||||
'upload_latency_p50_ms': round(statistics.median(timings) * 1000, 1),
|
||||
'upload_latency_max_ms': round(max(timings) * 1000, 1),
|
||||
'all_ready_elapsed_seconds': round(complete_seconds, 3),
|
||||
'bytes_per_file': len(source),
|
||||
'note': 'HTTP 202 = queued; readiness checked for all uploads. Capture API peak RSS separately via docker stats.',
|
||||
}
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(exist_ok=True, parents=True)
|
||||
output.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print('PASS: %d concurrent HTTP 202 uploads -> ready, 3 variants each' % args.concurrency)
|
||||
print(json.dumps(data, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5 negative API tests with isolated synthetic users (requires live stack)."""
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
from client import Client, arguments, run, check
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab5 negative file/ACL/security tests')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
base = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
data = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
c.call('POST', base+'big.png', 413, actor=alice, raw=data+b'\x00'*(10*1024*1024+1-len(data)), headers={'Content-Type':'image/png'})
|
||||
c.call('POST', base+'bad.png', 415, actor=alice, raw=b'not-an-image', headers={'Content-Type':'image/png'})
|
||||
c.call('POST', base+'fake.jpg', 415, actor=alice, raw=data, headers={'Content-Type':'image/jpeg'})
|
||||
c.call('POST', base+quote('../escape.png',safe=''), 400, actor=alice, raw=data, headers={'Content-Type':'image/png'})
|
||||
c.call('POST', base+'x.png', 404, actor=eve, raw=data, headers={'Content-Type':'image/png'})
|
||||
c.call('POST', base+'x.png', 401, raw=data, headers={'Content-Type':'image/png'})
|
||||
uploaded = c.attachment(alice,chat)[0]
|
||||
ready = c.wait_ready(alice, uploaded)
|
||||
unknown = str(uuid.uuid4())
|
||||
c.call('GET','/api/v1/attachments/'+unknown,404,actor=alice)
|
||||
c.call('GET','/api/v1/attachments/'+uploaded['id'],404,actor=eve)
|
||||
c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',404,actor=eve)
|
||||
# A ready Lab5 attachment has a downloadable thumbnail for chat members.
|
||||
# A non-member still gets 404, and an unknown variant must not resolve.
|
||||
c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content?variant=thumbnail',404,actor=eve)
|
||||
c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content?variant=nonexistent',404,actor=alice)
|
||||
check(any(v['name'] == 'thumbnail' for v in ready['variants']), 'missing thumbnail variant')
|
||||
thumb = c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content?variant=thumbnail',200,actor=alice)
|
||||
check(thumb['headers'].get_content_type() == 'image/jpeg', 'wrong thumbnail MIME')
|
||||
other_chat = c.call('POST','/api/v1/chats',201,actor=alice,
|
||||
body={'title':'Другой чат','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
|
||||
path = '/api/v1/chats/'+other_chat['id']+'/messages'
|
||||
c.call('POST',path,404,actor=alice,
|
||||
body={'text':'cross-chat','attachment_ids':[uploaded['id']]},
|
||||
headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=alice,
|
||||
body={'text':'unknown','attachment_ids':[unknown]},
|
||||
headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
ok = c.message(bob,chat,'',attachments=[uploaded['id']])['json']
|
||||
check(ok['attachment_ids']==[uploaded['id']], 'valid attachment not linked')
|
||||
print('PASS: lab5 negative image, MIME, size, filename, ACL, variants and cross-chat checks')
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab3 own test: 30 requests using identical actor/chat/key/body across both replicas."""
|
||||
import concurrent.futures
|
||||
import sys
|
||||
import uuid
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Check atomic idempotency across API replicas")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
body = {"text": "Concurrent replay " + key}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
def worker(_):
|
||||
# Independent request client; one shared bearer token and idempotency key.
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
return client.call("POST", path, expected=201, actor=alice, body=body,
|
||||
headers={"Idempotency-Key": key}, schema="Message")
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor:
|
||||
results = list(executor.map(worker, range(30)))
|
||||
ids = {result["json"]["id"] for result in results}
|
||||
instances = {result["headers"]["X-Instance-Id"] for result in results}
|
||||
check(len(ids) == 1, "parallel replay created different messages")
|
||||
check(len(instances) >= 2, "LB did not serve requests via both API replicas")
|
||||
check(all(r["json"] == results[0]["json"] for r in results), "replay returned altered result")
|
||||
c.call("POST", path, 409, actor=alice, body={"text": "different body"}, headers={"Idempotency-Key": key})
|
||||
c.call("POST", path, 201, actor=bob, body=body, headers={"Idempotency-Key": key}, schema="Message")
|
||||
history = c.call("GET", path + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check(sum(x["id"] in ids for x in history) == 1, "message duplicated in history")
|
||||
print("PASS: parallel idempotency across", len(instances), "replicas; one message, replay 201, conflicting body 409")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fast non-Docker checks for input contracts and cursor scoping."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from app.core import make_cursor, read_cursor, parse_limit, APIError
|
||||
from app.models import CreateUser, CreateChat, CreateMessage
|
||||
from pydantic import ValidationError
|
||||
|
||||
|
||||
def reject(fn):
|
||||
try:
|
||||
fn()
|
||||
except (APIError, ValidationError, ValueError):
|
||||
return
|
||||
raise AssertionError("Expected invalid input")
|
||||
|
||||
|
||||
def main():
|
||||
token = str(uuid.uuid4())
|
||||
dt = datetime.now(timezone.utc)
|
||||
cursor = make_cursor("messages", token, dt, str(uuid.uuid4()))
|
||||
assert read_cursor(cursor, "messages", token)[0] == dt
|
||||
reject(lambda: read_cursor(cursor, "messages", str(uuid.uuid4())))
|
||||
reject(lambda: read_cursor(cursor, "chats", token))
|
||||
assert parse_limit(None) == 50
|
||||
reject(lambda: parse_limit("0"))
|
||||
reject(lambda: parse_limit("101"))
|
||||
reject(lambda: CreateUser(username="user_name", display_name=" \t", password="Long-enough-secret"))
|
||||
reject(lambda: CreateUser(username="user_name", display_name="Test", password=" " * 3))
|
||||
assert CreateMessage(text="A\u0000B").text == "A\u0000B"
|
||||
reject(lambda: CreateMessage(text=" \t"))
|
||||
reject(lambda: CreateChat(title="title", member_ids=[token] * 2))
|
||||
reject(lambda: CreateChat(title="title", member_ids=[token] * 101))
|
||||
print("PASS: models, cursor scoping, limits, Unicode U+0000")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional *live* Lab5 fault tests; operator-controlled, synthetic records only.
|
||||
|
||||
broker-persistence: require a publisher-confirmed RabbitMQ message to survive
|
||||
broker restart without a running dispatcher or worker. This differs from the
|
||||
outbox-restoration tests where dispatcher publishes *after* broker recovery.
|
||||
|
||||
failed-replay: safely inject a deterministic checksum mismatch into one fresh
|
||||
synthetic attachment's DB metadata, verify permanent failure, restore the
|
||||
original hash, replay via the operator-only CLI, and verify success plus audit.
|
||||
|
||||
staging-cleanup: verify the staged S3 object is absent after ready (with a
|
||||
matching cleared staging_key in the DB).
|
||||
|
||||
No volumes are deleted. The test may stop/restart worker/dispatcher/broker;
|
||||
run only against a disposable LAB5 environment and never concurrently.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from client import Client, Failure, check, run
|
||||
from pipeline_resilience import verify_ready, wait_api
|
||||
|
||||
from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, expected=(0,), timeout=240):
|
||||
proc = subprocess.run(
|
||||
['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
||||
capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout,
|
||||
)
|
||||
if proc.returncode not in expected:
|
||||
# Don't print env vars, tokens or command stdout/stderr by default.
|
||||
raise Failure('docker compose %s failed (exit %d); inspect ps/logs' %
|
||||
(' '.join(args[:2]), proc.returncode))
|
||||
return proc.stdout.strip()
|
||||
|
||||
|
||||
def pg(sql):
|
||||
"""Read-only or deliberately scoped fault SQL; UUIDs never user-supplied here."""
|
||||
user = compose('exec', '-T', 'postgres', 'printenv', 'POSTGRES_USER').strip()
|
||||
dbname = compose('exec', '-T', 'postgres', 'printenv', 'POSTGRES_DB').strip()
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-X', '-q', '-A', '-t',
|
||||
'-v', 'ON_ERROR_STOP=1', '-U', user, '-d', dbname, '-c', sql)
|
||||
|
||||
|
||||
def scalar(sql):
|
||||
return pg(sql).splitlines()[-1].strip()
|
||||
|
||||
|
||||
def wait_for(label, action, predicate, seconds=30, interval=0.5):
|
||||
deadline = time.monotonic() + seconds
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
last = action()
|
||||
if predicate(last):
|
||||
return last
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(interval)
|
||||
raise Failure('timed out waiting for ' + label + ', last=' + str(last)[:100])
|
||||
|
||||
|
||||
def job_query(att_id, fields):
|
||||
uuid.UUID(att_id)
|
||||
return scalar('SELECT %s FROM processing_jobs WHERE attachment_id = \'%s\'' %
|
||||
(fields, att_id))
|
||||
|
||||
|
||||
def queue_ready():
|
||||
out = compose('exec', '-T', 'broker', 'rabbitmqctl', '-q', 'list_queues',
|
||||
'name', 'messages_ready', 'messages_unacknowledged')
|
||||
for line in out.splitlines():
|
||||
parts = re.split(r'\s+', line.strip())
|
||||
if parts[0] == 'attachment-processing.v1' and len(parts) >= 3:
|
||||
return int(parts[1]), int(parts[2])
|
||||
raise Failure('RabbitMQ durable queue missing')
|
||||
|
||||
|
||||
def make_upload(c):
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att, original = c.attachment(alice, chat)
|
||||
check(att['status'] == 'queued', 'upload must return 202 queued')
|
||||
uuid.UUID(att['id'])
|
||||
return alice, bob, att, original
|
||||
|
||||
|
||||
def wait_staging_cleared(att_id, seconds=20):
|
||||
return wait_for('staging_key cleared after ready',
|
||||
lambda: scalar("SELECT COALESCE(staging_key,'<NULL>') FROM attachments WHERE id='%s'" % att_id),
|
||||
lambda value: value == '<NULL>', seconds=seconds)
|
||||
|
||||
|
||||
def verify_staging_absent(att_id):
|
||||
# This executes *inside* the worker container with its normal S3 credentials.
|
||||
# Never expose S3 secrets to the host or write them to evidence files.
|
||||
code = '''import sys
|
||||
from botocore.exceptions import ClientError
|
||||
from app.attachments import s3_client, BUCKET
|
||||
key='staging/'+sys.argv[1]+'/original'
|
||||
try:
|
||||
s3_client().head_object(Bucket=BUCKET,Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response.get('ResponseMetadata',{}).get('HTTPStatusCode')==404:
|
||||
print('ABSENT')
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
print('STILL_PRESENT')'''
|
||||
result = compose('exec', '-T', 'worker', 'python', '-c', code, att_id)
|
||||
check(result == 'ABSENT', 'staging S3 object still present: ' + result[:70])
|
||||
|
||||
|
||||
def broker_persistence(c):
|
||||
compose('stop', 'worker')
|
||||
compose('up', '-d', 'dispatcher')
|
||||
baseline = queue_ready()[0]
|
||||
alice, _bob, att, original = make_upload(c)
|
||||
print('202 queued:', att['id'], flush=True)
|
||||
sql = "SELECT COALESCE(bool_and(published_at IS NOT NULL),false) FROM job_outbox WHERE job_id=(SELECT id FROM processing_jobs WHERE attachment_id='%s')" % att['id']
|
||||
wait_for('outbox publisher confirm', lambda: scalar(sql), lambda v: v == 't', seconds=30)
|
||||
wait_for('message in RabbitMQ ready queue', lambda: queue_ready()[0],
|
||||
lambda n: n >= baseline + 1, seconds=15)
|
||||
compose('stop', 'dispatcher')
|
||||
before = queue_ready()[0]
|
||||
check(before >= baseline + 1, 'published message disappeared before restart')
|
||||
print('Publisher confirmed; dispatcher and worker stopped; broker queue ready=%d' % before, flush=True)
|
||||
compose('restart', 'broker')
|
||||
compose('up', '-d', '--wait', 'broker')
|
||||
after = wait_for('RabbitMQ queue restoration', lambda: queue_ready()[0],
|
||||
lambda n: n >= before, seconds=40, interval=1)
|
||||
check(scalar(sql) == 't', 'outbox publish confirmation lost')
|
||||
print('Broker restarted; ready messages persisted=%d' % after, flush=True)
|
||||
# CRITICAL: do NOT restart dispatcher yet; only the restored RabbitMQ message
|
||||
# can deliver this job to the worker.
|
||||
compose('up', '-d', 'worker')
|
||||
verify_ready(c, alice, att, original, seconds=180)
|
||||
check(job_query(att['id'], 'status') == 'ready', 'job not committed ready')
|
||||
print('PASS: broker-persistence, confirmed RabbitMQ message survives broker restart without outbox republish')
|
||||
|
||||
|
||||
def failed_replay(c):
|
||||
compose('stop', 'worker', 'dispatcher')
|
||||
alice, _bob, att, original = make_upload(c)
|
||||
ident = att['id']
|
||||
original_sha = hashlib.sha256(original).hexdigest()
|
||||
check(original_sha == att['sha256'], 'fixture hash mismatch')
|
||||
check(scalar("SELECT sha256 FROM attachments WHERE id='%s'" % ident) == original_sha,
|
||||
'DB hash unexpected before controlled fault')
|
||||
fault_sha = '0' * 64 if original_sha != '0' * 64 else 'f' * 64
|
||||
changed = False
|
||||
try:
|
||||
updated = pg("UPDATE attachments SET sha256='%s' WHERE id='%s' AND status='queued' RETURNING id" %
|
||||
(fault_sha, ident))
|
||||
check(ident in updated, 'failed to inject synthetic checksum mismatch')
|
||||
changed = True
|
||||
compose('up', '-d', 'dispatcher', 'worker')
|
||||
|
||||
def get_state():
|
||||
return c.call('GET', '/api/v1/attachments/' + ident, actor=alice, schema='Attachment')['json']
|
||||
failed = wait_for('permanent failed status', get_state,
|
||||
lambda a: a['status'] == 'failed', seconds=90)
|
||||
check(failed['error_code'] == 'invalid_image',
|
||||
'expected permanent invalid_image, got ' + str(failed['error_code']))
|
||||
check(job_query(ident, 'status') == 'failed', 'processing job must fail')
|
||||
check(job_query(ident, 'attempt') == '1', 'permanent error must not retry')
|
||||
check(scalar("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % ident) == '0',
|
||||
'failed job created variants')
|
||||
print('Permanent invalid_image confirmed; no retry and no variant rows', flush=True)
|
||||
# Repair only the generated synthetic row before explicit operator replay.
|
||||
restored = pg("UPDATE attachments SET sha256='%s' WHERE id='%s' AND status='failed' RETURNING id" %
|
||||
(original_sha, ident))
|
||||
check(ident in restored, 'synthetic metadata could not be restored')
|
||||
changed = False
|
||||
compose('exec', '-T', 'dispatcher', 'python', '-m', 'app.jobs', 'replay', '--id', ident)
|
||||
verify_ready(c, alice, att, original, seconds=180)
|
||||
audit = scalar("SELECT count(*) FROM job_replay_audit WHERE job_id=(SELECT id FROM processing_jobs WHERE attachment_id='%s')" % ident)
|
||||
check(audit == '1', 'operator replay audit count incorrect: ' + audit)
|
||||
check(job_query(ident, 'status') == 'ready', 'replayed job not ready')
|
||||
attempt = job_query(ident, 'attempt')
|
||||
check(attempt == '1', 'replay did not reset attempt: ' + attempt)
|
||||
invalid = compose('exec', '-T', 'dispatcher', 'python', '-m', 'app.jobs',
|
||||
'replay', '--id', ident, expected=(1,))
|
||||
print('PASS: failed-replay; permanent failure → metadata repaired → replay → ready; audit=1; replay of ready rejected')
|
||||
finally:
|
||||
if changed:
|
||||
# Never leave the synthetic attachment with altered metadata.
|
||||
pg("UPDATE attachments SET sha256='%s' WHERE id='%s'" % (original_sha, ident))
|
||||
|
||||
|
||||
def staging_cleanup(c):
|
||||
compose('up', '-d', 'dispatcher', 'worker')
|
||||
alice, _bob, att, original = make_upload(c)
|
||||
verify_ready(c, alice, att, original, seconds=180)
|
||||
wait_staging_cleared(att['id'], seconds=30)
|
||||
verify_staging_absent(att['id'])
|
||||
print('PASS: staging-cleanup; ready, DB staging_key=NULL, original staging object absent in S3')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--scenario', required=True,
|
||||
choices=['broker-persistence', 'failed-replay', 'staging-cleanup'])
|
||||
args = parser.parse_args()
|
||||
if os.getenv('LAB5_ALLOW_FAILURE_TEST') != 'yes':
|
||||
raise Failure('Set LAB5_ALLOW_FAILURE_TEST=yes; run only on your isolated Lab5 stack')
|
||||
c = Client('http://localhost:8080')
|
||||
try:
|
||||
wait_api()
|
||||
if args.scenario == 'broker-persistence':
|
||||
broker_persistence(c)
|
||||
elif args.scenario == 'failed-replay':
|
||||
failed_replay(c)
|
||||
else:
|
||||
staging_cleanup(c)
|
||||
finally:
|
||||
# Restore normal services even when an assertion fails. NO volume deletion.
|
||||
try:
|
||||
compose('up', '-d', '--wait', 'broker')
|
||||
compose('up', '-d', 'dispatcher', 'worker')
|
||||
except Failure:
|
||||
print('WARNING: inspect docker compose ps and restore dispatcher/worker manually')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator evidence for Lab5 queue durability and failure windows.
|
||||
|
||||
Runs only on an isolated lab5 Compose stack. Never resets named volumes. The test
|
||||
preserves user/session secrets strictly in process memory and prints no tokens.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, Failure, check, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, expected=(0,)):
|
||||
p = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=240)
|
||||
if p.returncode not in expected:
|
||||
raise Failure('docker compose command failed: %s (exit %s); inspect docker compose ps/logs'
|
||||
% (' '.join(args[:2]), p.returncode))
|
||||
return p
|
||||
|
||||
|
||||
def wait_api(timeout=60):
|
||||
import urllib.request
|
||||
deadline=time.monotonic()+timeout
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
with urllib.request.urlopen('http://localhost:8080/health/ready', timeout=2) as r:
|
||||
if r.status==200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(.5)
|
||||
raise Failure('API did not become ready')
|
||||
|
||||
|
||||
def make_queued(client):
|
||||
alice,bob,eve,chat=client.bootstrap()
|
||||
att,original=client.attachment(alice,chat)
|
||||
check(att['status']=='queued','202 must return queued snapshot')
|
||||
c=client.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=alice)
|
||||
attached=client.message(alice,chat,'',attachments=[att['id']])['json']
|
||||
check(attached['attachment_ids']==[att['id']],'queued attachment cannot be linked')
|
||||
return alice,bob,att,original
|
||||
|
||||
|
||||
def verify_ready(client,actor,att,original,seconds=180):
|
||||
r=client.wait_ready(actor,att,wait_seconds=seconds)
|
||||
check(len(r['variants']) == 3, 'expected exactly three variants, no duplicate entries')
|
||||
variants={v['name']:v for v in r['variants']}
|
||||
check(set(variants)=={'thumbnail','crop','optimized'},'missing/extra variants')
|
||||
check((variants['thumbnail']['width'],variants['thumbnail']['height'])==(256,160), 'thumbnail dimensions')
|
||||
check((variants['crop']['width'],variants['crop']['height'])==(128,128), 'crop dimensions')
|
||||
raw=client.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=actor)
|
||||
check(raw['bytes']==original,'original changed across asynchronous pipeline')
|
||||
for name in ('thumbnail','crop','optimized'):
|
||||
v=variants[name]
|
||||
response=client.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+name,actor=actor)
|
||||
check(len(response['bytes'])==v['size_bytes'] and hashlib.sha256(response['bytes']).hexdigest()==v['sha256'],
|
||||
'variant checksum mismatch: '+name)
|
||||
return r
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--scenario',choices=['paused','outbox-crash','worker-crash'],required=True)
|
||||
args=parser.parse_args()
|
||||
if os.getenv('LAB5_ALLOW_FAILURE_TEST')!='yes':
|
||||
raise Failure('Set LAB5_ALLOW_FAILURE_TEST=yes in PowerShell to run destructive failure test')
|
||||
c=Client('http://localhost:8080')
|
||||
# All tests make a fresh attachment while dispatcher/worker are stopped.
|
||||
compose('stop','worker','dispatcher')
|
||||
try:
|
||||
alice,bob,att,original=make_queued(c)
|
||||
print('Created durable queued attachment',att['id'],flush=True)
|
||||
if args.scenario=='paused':
|
||||
compose('restart','api1','api2','broker')
|
||||
compose('up','-d','--wait','broker')
|
||||
wait_api()
|
||||
elif args.scenario=='outbox-crash':
|
||||
# Transaction committed, dispatcher crashes before publish.
|
||||
compose('run','--rm','-e','LAB5_FAULT_BEFORE_PUBLISH=once',
|
||||
'dispatcher',expected=(78,))
|
||||
print('Injected dispatcher exit 78 after committed outbox, before publish')
|
||||
else:
|
||||
compose('up','-d','dispatcher')
|
||||
# Fault after all S3 writes and before PostgreSQL result COMMIT and ack.
|
||||
compose('run','--rm','-e','LAB5_FAULT_AFTER_S3=once',
|
||||
'worker',expected=(77,))
|
||||
print('Injected worker exit 77 after S3 effects, before result/ack')
|
||||
compose('up','-d','dispatcher','worker')
|
||||
wait_api()
|
||||
ready=verify_ready(c,bob,att,original)
|
||||
check(ready['status']=='ready','attachment not ready')
|
||||
print('PASS:',args.scenario,'durable queued->ready; original/3 variants verified; no duplicates')
|
||||
finally:
|
||||
# Restore the normal topology even after an assertion failure.
|
||||
compose('up','-d','dispatcher','worker')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user