203 lines
12 KiB
Python
203 lines
12 KiB
Python
import hashlib
|
|
import io
|
|
import json
|
|
import time
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
from types import SimpleNamespace
|
|
from uuid import uuid4
|
|
|
|
from PIL import Image
|
|
|
|
|
|
def check(args, lab, retry=False):
|
|
c = lab.client(args)
|
|
actor, bob, eve, chat = c.bootstrap()
|
|
|
|
def sql(statement):
|
|
return lab.compose(args, 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger',
|
|
'-v', 'ON_ERROR_STOP=1', '-At', '-c', statement, quiet=True).strip()
|
|
|
|
def wait(predicate, seconds=60):
|
|
end = time.monotonic() + seconds
|
|
while time.monotonic() < end:
|
|
if predicate():
|
|
return
|
|
time.sleep(0.2)
|
|
raise RuntimeError('Pipeline test condition timed out')
|
|
|
|
def ready(att):
|
|
done = c.wait_ready(actor, att)
|
|
path = '/api/v1/attachments/' + att['id'] + '/content'
|
|
raw = c.call('GET', path, actor=bob)['bytes']
|
|
if hashlib.sha256(raw).hexdigest() != att['sha256']:
|
|
raise RuntimeError('Original checksum changed')
|
|
thumb = c.call('GET', path + '?variant=thumbnail', actor=bob)['bytes']
|
|
with Image.open(io.BytesIO(thumb)) as image:
|
|
if image.format != 'JPEG' or image.size != (256, 160):
|
|
raise RuntimeError('Thumbnail format or size mismatch')
|
|
if hashlib.sha256(thumb).hexdigest() != done['variants'][0]['sha256']:
|
|
raise RuntimeError('Thumbnail checksum mismatch')
|
|
return done
|
|
|
|
def duplicate(att):
|
|
code = ('from src.storage import PostgresStore; from src.broker import publish,envelope; '
|
|
's=PostgresStore(); s.open()\n'
|
|
'with s.connection() as c: j=c.execute("SELECT * FROM attachment_jobs WHERE attachment_id=%s",'
|
|
'("' + att['id'] + '",)).fetchone()\n'
|
|
'publish(envelope(j)); publish(envelope(j)); s.close()')
|
|
lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', code, quiet=True)
|
|
def drained():
|
|
lines = lab.compose(args, 'exec', '-T', 'broker', 'rabbitmqctl', '-q',
|
|
'list_queues', '-p', 'messenger', 'name', 'messages', quiet=True)
|
|
return any(line.split() == ['attachment.process.v1', '0'] for line in lines.splitlines())
|
|
wait(drained, 30)
|
|
now = c.call('GET', '/api/v1/attachments/' + att['id'], actor=actor, schema='Attachment')['json']
|
|
if now != att:
|
|
raise RuntimeError('Duplicate delivery changed ready metadata')
|
|
|
|
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
|
try:
|
|
attachment, original = c.attachment(actor, chat)
|
|
path = '/api/v1/attachments/' + attachment['id']
|
|
if not retry:
|
|
from jsonschema import Draft202012Validator, FormatChecker
|
|
job_row = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + attachment['id'] + "'"))
|
|
carrier = {'schema_version': 1, 'job_id': job_row['id'], 'attachment_id': attachment['id'],
|
|
'type': 'attachment.process.v1', 'pipeline_version': 1, 'attempt': 1,
|
|
'created_at': job_row['created_at']}
|
|
schema = json.loads((lab.ROOT / 'contracts/jobs.schema.json').read_text())
|
|
Draft202012Validator(schema, format_checker=FormatChecker()).validate(carrier)
|
|
anonymous = (
|
|
"import os,boto3; from botocore import UNSIGNED; from botocore.config import Config; "
|
|
"from botocore.exceptions import ClientError\n"
|
|
"c=boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],config=Config(signature_version=UNSIGNED,proxies={}))\n"
|
|
"try:\n r=c.get_object(Bucket=os.environ['S3_BUCKET'],Key='system/readiness'); r['Body'].close(); status=200\n"
|
|
"except ClientError as e:\n status=e.response['ResponseMetadata']['HTTPStatusCode']\n"
|
|
"assert status==403; print(status)"
|
|
)
|
|
if lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', anonymous, quiet=True).strip() != '403':
|
|
raise RuntimeError('Anonymous S3 access allowed')
|
|
linked = c.message(actor, chat, '', attachments=[attachment['id']])['json']
|
|
for variant in ('original', 'thumbnail'):
|
|
c.call('GET', path + '/content?variant=' + variant, 409, actor=bob)
|
|
c.call('GET', path, 404, actor=eve)
|
|
c.message(bob, chat, 'worker is stopped')
|
|
before = lab.states(args)
|
|
lab.compose(args, 'restart', '--timeout', '10', 'api1', 'api2', 'broker')
|
|
lab.wait_ready(args)
|
|
after = lab.states(args)
|
|
for name in ('api1', 'api2', 'broker'):
|
|
if before[name]['started_at'] == after[name]['started_at'] or before[name]['volumes'] != after[name]['volumes']:
|
|
raise RuntimeError('Queue restart evidence mismatch')
|
|
queued = c.call('GET', path, actor=actor, schema='Attachment')['json']
|
|
if queued['status'] != 'queued':
|
|
raise RuntimeError('Stopped worker unexpectedly processed the upload')
|
|
lab.compose(args, 'start', 'worker')
|
|
done = ready(attachment)
|
|
duplicate(done)
|
|
c.call('GET', path + '/content?variant=crop', 404, actor=bob)
|
|
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob, schema='MessagePage')['json']['items']
|
|
if linked not in history:
|
|
raise RuntimeError('Queued attachment message was lost')
|
|
result = {'status': 'PASS', 'upload_with_stopped_worker': 202, 'pending_content': 409,
|
|
'same_attachment_after_api_broker_restart': True, 'original_and_thumbnail': 'PASS',
|
|
'duplicate_noop': 'PASS', 'job_schema': 'PASS', 'anonymous_s3': 403, 'before': before, 'after': after}
|
|
lab.evidence('queue.json', result)
|
|
lab.say('PASS: accepted upload survived API/broker restart; thumbnail and duplicate delivery checked')
|
|
return result
|
|
|
|
job = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + attachment['id'] + "'"))
|
|
sql("UPDATE attachment_jobs SET staging_key='missing-test/" + attachment['id'] + "' WHERE id='" + job['id'] + "'")
|
|
lab.compose(args, 'start', 'worker')
|
|
wait(lambda: int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + job['id'] + "'")) >= 1)
|
|
sql("UPDATE attachment_jobs SET staging_key='" + job['staging_key'] + "' WHERE id='" + job['id'] + "'")
|
|
ready(attachment)
|
|
attempts = int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + job['id'] + "'"))
|
|
if attempts < 2:
|
|
raise RuntimeError('Transient error did not cause a retry')
|
|
|
|
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
|
failed, _ = c.attachment(actor, chat)
|
|
failed_job = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + failed['id'] + "'"))
|
|
sql("UPDATE attachment_jobs SET staging_key='missing-test/" + failed['id'] + "' WHERE id='" + failed_job['id'] + "'")
|
|
lab.compose(args, 'start', 'worker')
|
|
wait(lambda: sql("SELECT status FROM attachments WHERE id='" + failed['id'] + "'") == 'failed', 75)
|
|
state = c.call('GET', '/api/v1/attachments/' + failed['id'], actor=actor, schema='Attachment')['json']
|
|
count = int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + failed_job['id'] + "'"))
|
|
if count != 5 or state['error_code'] != 'retry_exhausted':
|
|
raise RuntimeError('Retry budget was not enforced')
|
|
c.call('GET', '/api/v1/attachments/' + failed['id'] + '/content', 409, actor=actor)
|
|
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor,
|
|
body={'text': '', 'attachment_ids': [failed['id']]}, headers={'Idempotency-Key': uuid4().hex})
|
|
sql("UPDATE attachment_jobs SET staging_key='" + failed_job['staging_key'] + "' WHERE id='" + failed_job['id'] + "'")
|
|
|
|
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
|
corrupt, _ = c.attachment(actor, chat)
|
|
stage = sql("SELECT staging_key FROM attachment_jobs WHERE attachment_id='" + corrupt['id'] + "'")
|
|
code = ("from src.objects import Objects; from io import BytesIO; o=Objects(); "
|
|
"o.put(" + repr(stage) + ",BytesIO(b'broken'),6,'image/png'); o.close()")
|
|
lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', code, quiet=True)
|
|
lab.compose(args, 'start', 'worker')
|
|
wait(lambda: sql("SELECT status FROM attachments WHERE id='" + corrupt['id'] + "'") == 'failed')
|
|
if sql("SELECT error_code FROM attachments WHERE id='" + corrupt['id'] + "'") != 'invalid_image':
|
|
raise RuntimeError('Permanent image error was not classified')
|
|
if sql("SELECT attempt FROM attachment_jobs WHERE attachment_id='" + corrupt['id'] + "'") != '1':
|
|
raise RuntimeError('Permanent error retried')
|
|
|
|
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
|
crash, _ = c.attachment(actor, chat)
|
|
function = 'test_pause_' + uuid4().hex
|
|
sql("CREATE FUNCTION " + function + "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(30); RETURN NEW; END $$; "
|
|
"CREATE TRIGGER " + function + " BEFORE INSERT ON attachment_variants FOR EACH ROW "
|
|
"WHEN (NEW.attachment_id='" + crash['id'] + "'::uuid) EXECUTE FUNCTION " + function + "()")
|
|
try:
|
|
lab.compose(args, 'start', 'worker')
|
|
wait(lambda: sql("SELECT count(*) FROM pg_stat_activity WHERE wait_event='PgSleep'") != '0')
|
|
if sql("SELECT status FROM attachments WHERE id='" + crash['id'] + "'") != 'processing':
|
|
raise RuntimeError('Processing state not observed')
|
|
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
|
finally:
|
|
sql('DROP TRIGGER IF EXISTS ' + function + ' ON attachment_variants; DROP FUNCTION IF EXISTS ' + function + '()')
|
|
lab.compose(args, 'start', 'worker')
|
|
ready(crash)
|
|
if sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='" + crash['id'] + "'") != '1':
|
|
raise RuntimeError('Worker restart duplicated variants')
|
|
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
|
pending, _ = c.attachment(actor, chat)
|
|
sql("UPDATE attachment_jobs SET created_at=clock_timestamp()-INTERVAL '25 hours' "
|
|
"WHERE attachment_id='" + pending['id'] + "'; UPDATE attachments SET "
|
|
"updated_at=clock_timestamp()-INTERVAL '25 hours' WHERE id='" + failed['id'] + "'")
|
|
cleanup = ('from src.storage import PostgresStore; from src.objects import Objects; '
|
|
'from src.cleanup import clean_once; s=PostgresStore(); s.open(); o=Objects(); '
|
|
'clean_once(s,o); o.close(); s.close()')
|
|
lab.compose(args, 'exec', '-T', 'cleanup', 'python', '-c', cleanup, quiet=True)
|
|
if sql("SELECT status || ':' || staging_deleted FROM attachments WHERE id='" + pending['id'] + "'") != 'queued:false':
|
|
raise RuntimeError('Cleanup removed accepted waiting work')
|
|
if sql("SELECT staging_deleted FROM attachments WHERE id='" + failed['id'] + "'") != 't':
|
|
raise RuntimeError('Expired failed staging was not cleaned')
|
|
if sql("SELECT staging_deleted FROM attachments WHERE id='" + corrupt['id'] + "'") != 'f':
|
|
raise RuntimeError('Fresh failed staging was removed early')
|
|
ready(attachment)
|
|
lab.compose(args, 'start', 'worker')
|
|
ready(pending)
|
|
result = {'status': 'PASS', 'transient_attempts': attempts, 'max_attempts': count,
|
|
'failed_content': 409, 'failed_link': 409, 'processing_observed': True,
|
|
'permanent_error_attempts': 1, 'worker_stopped_before_result_commit': True,
|
|
'staging_retention_and_pending_protection': True, 'redelivery_same_result': True}
|
|
lab.evidence('retry.json', result)
|
|
lab.say('PASS: retry recovery, final failed and real worker interruption')
|
|
return result
|
|
finally:
|
|
lab.compose(args, 'start', 'worker')
|
|
lab.wait_ready(args)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
from scripts import lab
|
|
args = SimpleNamespace(project=os.environ['LAB6_PROJECT'], port=int(os.environ['LAB6_PORT']),
|
|
ttl=int(os.environ['LAB6_TTL']), test_port=18089)
|
|
check(args, lab, retry=sys.argv[1] == 'retry')
|