"""Track 2: real S3 PUT + rolled-back SQL, missing bytes, safe repeated repairs.""" import datetime as dt import json from pathlib import Path import sys import time import uuid sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests')) sys.path.insert(0,str(Path(__file__).resolve().parents[1])) from client import Client, check from src.storage import BUCKET, PREFIX, db, s3 from src.reconcile import reconcile def main(): client = s3() c = Client('http://lb:8080') alice,bob,eve,chat = c.bootstrap() used,raw = c.attachment(alice,chat) c.message(alice,chat,'keep',attachments=[used['id']]) missing,_ = c.attachment(alice,chat) with db() as con: rows = con.execute('SELECT * FROM attachments WHERE id=ANY(%s::uuid[])',([used['id'],missing['id']],)).fetchall() keys = {str(row['id']):row['object_key'] for row in rows} def all_keys(): return {obj['Key'] for page in client.get_paginator('list_objects_v2').paginate(Bucket=BUCKET,Prefix=PREFIX) for obj in page.get('Contents',[])} before = all_keys() # Failure injection is entirely in the test DB, not a production HTTP switch. # A filename-specific trigger aborts the real API INSERT, after its real PUT. marker = 'inject-'+uuid.uuid4().hex+'.png' with db() as con: con.execute("""CREATE OR REPLACE FUNCTION lab4_inject_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename LIKE 'inject-%%' THEN RAISE EXCEPTION 'synthetic commit-path failure'; END IF; RETURN NEW; END $$""") con.execute('CREATE TRIGGER lab4_inject BEFORE INSERT ON attachments ' 'FOR EACH ROW EXECUTE FUNCTION lab4_inject_failure()') try: c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+marker,500, actor=alice,raw=raw,headers={'Content-Type':'image/png'}) finally: with db() as con: con.execute('DROP TRIGGER IF EXISTS lab4_inject ON attachments') con.execute('DROP FUNCTION IF EXISTS lab4_inject_failure()') new_keys = all_keys()-before check(len(new_keys)==1,'failed real upload must leave exactly one orphan') orphan = new_keys.pop() client.delete_object(Bucket=BUCKET,Key=keys[missing['id']]) with db() as con: con.execute("UPDATE attachments SET created_at=clock_timestamp()-interval '2 hours' WHERE id=ANY(%s::uuid[])", ([used['id'],missing['id']],)) early = reconcile(True,60) check(orphan not in early['orphan'],'fresh orphan deleted') # LIST timestamps are assigned by S3, not forged. Wait for genuine grace expiry. time.sleep(62) fresh = PREFIX+'fresh-'+uuid.uuid4().hex client.put_object(Bucket=BUCKET,Key=fresh,Body=raw) preview = reconcile(False,60) check(orphan in preview['orphan'] and missing['id'] in preview['missing'],'dry-run missed discrepancies') check(client.head_object(Bucket=BUCKET,Key=orphan)['ContentLength']==len(raw),'dry-run mutated S3') applied = reconcile(True,60) check(orphan in applied['orphan'],'orphan not removed') check(client.head_object(Bucket=BUCKET,Key=fresh)['ContentLength']==len(raw),'fresh deleted') check(c.call('GET','/api/v1/attachments/'+used['id']+'/content',actor=bob)['bytes']==raw,'used attachment deleted') c.call('GET','/api/v1/attachments/'+missing['id'],409,actor=alice) again = reconcile(True,60) check(not again['orphan'],'second run repeated deletion') client.put_object(Bucket=BUCKET,Key=keys[missing['id']],Body=b'bad-backup') wrong = reconcile(True,60) check(missing['id'] not in wrong['repaired'],'corrupt backup published') client.put_object(Bucket=BUCKET,Key=keys[missing['id']],Body=raw,ContentType='image/png') restored = reconcile(True,60) check(missing['id'] in restored['repaired'],'backup not restored') check(c.call('GET','/api/v1/attachments/'+missing['id']+'/content',actor=bob)['bytes']==raw,'restored bytes mismatch') # Force pagination (>1000 keys); new objects must all survive even --apply. scale_prefix = PREFIX+'scale-'+uuid.uuid4().hex+'-' import concurrent.futures with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool: list(pool.map(lambda n:client.put_object(Bucket=BUCKET,Key=scale_prefix+str(n),Body=b'x'),range(1005))) scaled = reconcile(False,3600) check(scaled['list_requests']>=2,'pagination not tested') # Clean only the exact keys this scenario owns (operator test cleanup). for start in (0,1000): client.delete_objects(Bucket=BUCKET,Delete={'Objects':[{'Key':scale_prefix+str(i)} for i in range(start,min(start+1000,1005))]}) client.delete_object(Bucket=BUCKET,Key=fresh) print(json.dumps({'result':'PASS','early':early,'dry_run':preview,'apply':applied, 'repeat':again,'wrong_backup':wrong,'restore':restored,'scale':scaled},indent=2)) if __name__ == '__main__': main()