forked from mtusi2026/mtusi2026lab4
102 lines
5.4 KiB
Python
102 lines
5.4 KiB
Python
"""Inject real orphan/missing failures using a dedicated operator-only test container."""
|
|
import concurrent.futures as cf
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import time
|
|
import uuid
|
|
import boto3
|
|
from botocore.exceptions import ClientError
|
|
|
|
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, setting
|
|
from src.reconcile import reconcile
|
|
|
|
|
|
def main():
|
|
os.environ['S3_ACCESS_KEY_ID_FILE'] = '/run/secrets/reconcile_access_key_id'
|
|
os.environ['S3_SECRET_ACCESS_KEY_FILE'] = '/run/secrets/reconcile_secret_access_key'
|
|
c = Client('http://lb:8080',timeout=40)
|
|
a,b,e,chat = c.bootstrap()
|
|
content = Path('tests/fixtures/sample.png').read_bytes()
|
|
att,_ = c.attachment(a,chat)
|
|
c.message(a,chat,'used attachment',attachments=[att['id']])
|
|
with db() as conn:
|
|
used = conn.execute('SELECT * FROM attachments WHERE id=%s',(att['id'],)).fetchone()
|
|
# Only the tests profile has root credentials; normal API/reconciler do not.
|
|
admin = boto3.client('s3',endpoint_url='http://s3:9000',region_name='us-east-1',
|
|
aws_access_key_id=setting('MINIO_ROOT_USER'),aws_secret_access_key=setting('MINIO_ROOT_PASSWORD'))
|
|
old_key = PREFIX+str(uuid.uuid4())
|
|
admin.put_object(Bucket=BUCKET,Key=old_key,Body=content)
|
|
# Real API error after PUT and before INSERT/COMMIT, through a test-only process.
|
|
fault = Client('http://fault-api:8080')
|
|
fault.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=fault.png',503,
|
|
actor=a,raw=content,headers={'Content-Type':'image/png'})
|
|
# A deferred PostgreSQL trigger raises a real error at COMMIT, after S3 PUT.
|
|
with db() as conn:
|
|
conn.execute("""CREATE OR REPLACE FUNCTION test_commit_fault() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
BEGIN IF NEW.filename='commit-fault.png' THEN RAISE EXCEPTION 'test commit failure'; END IF; RETURN NEW; END $$""")
|
|
conn.execute('DROP TRIGGER IF EXISTS test_commit_fault ON attachments')
|
|
conn.execute('CREATE CONSTRAINT TRIGGER test_commit_fault AFTER INSERT ON attachments DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION test_commit_fault()')
|
|
try:
|
|
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=commit-fault.png',503,
|
|
actor=a,raw=content,headers={'Content-Type':'image/png'})
|
|
finally:
|
|
with db() as conn:
|
|
conn.execute('DROP TRIGGER IF EXISTS test_commit_fault ON attachments')
|
|
conn.execute('DROP FUNCTION IF EXISTS test_commit_fault()')
|
|
time.sleep(3)
|
|
fresh_key = PREFIX+str(uuid.uuid4())
|
|
admin.put_object(Bucket=BUCKET,Key=fresh_key,Body=content)
|
|
dry = reconcile(False,2,7)
|
|
check(dry['orphan_candidates']>=3 and dry['deleted']==0,'dry-run did not find failures safely')
|
|
admin.head_object(Bucket=BUCKET,Key=old_key)
|
|
applied = reconcile(True,2,7)
|
|
check(applied['deleted']>=3,'old orphans not removed')
|
|
admin.head_object(Bucket=BUCKET,Key=fresh_key)
|
|
admin.head_object(Bucket=BUCKET,Key=used['object_key'])
|
|
repeat = reconcile(True,2,7)
|
|
check(repeat['deleted']==0,'repeat immediately deleted fresh object')
|
|
# S3 loss: metadata + message link are retained, grace observations precede quarantine.
|
|
admin.delete_object(Bucket=BUCKET,Key=used['object_key'])
|
|
missing_dry = reconcile(False,2,7)
|
|
check(missing_dry['missing']>=1 and missing_dry['observation_started']==0,'dry-run changed DB')
|
|
first = reconcile(True,2,7)
|
|
check(first['observation_started']>=1 and first['quarantined']==0,'fresh absence quarantined too early')
|
|
time.sleep(3)
|
|
second = reconcile(True,2,7)
|
|
check(second['quarantined']>=1,'persistent missing object not quarantined')
|
|
c.call('GET','/api/v1/attachments/'+att['id']+'/content',503,actor=b)
|
|
with db() as conn:
|
|
check(conn.execute('SELECT 1 FROM message_attachments WHERE attachment_id=%s',(att['id'],)).fetchone(),'used metadata lost')
|
|
admin.put_object(Bucket=BUCKET,Key=used['object_key'],Body=content,
|
|
ContentType='image/png',Metadata={'sha256':used['sha256']})
|
|
restored = reconcile(True,2,7)
|
|
check(restored['recovered']>=1,'restored bytes not verified/recovered')
|
|
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']==content,'restored content mismatch')
|
|
# Reconciliation concurrent with PUT/COMMIT cannot collect valid attachments.
|
|
def uploading(_):
|
|
return c.attachment(a,chat)[0]
|
|
with cf.ThreadPoolExecutor(max_workers=11) as executor:
|
|
futures = [executor.submit(uploading,i) for i in range(10)]
|
|
scan = executor.submit(reconcile,True,2,7)
|
|
uploaded = [f.result() for f in futures]
|
|
concurrent = scan.result()
|
|
for item in uploaded:
|
|
check(c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=b)['bytes']==content,'concurrent sweep lost fresh upload')
|
|
# A cost sweep over > one page of objects/rows.
|
|
cost = [reconcile(False,3600,7) for _ in range(3)]
|
|
print(json.dumps({'status':'PASS','grace_for_test_seconds':2,'dry_run':dry,
|
|
'apply':applied,'repeat':repeat,'missing_dry_run':missing_dry,
|
|
'first_missing_observation':first,'quarantine':second,'restore':restored,
|
|
'concurrent_scan':concurrent,'concurrent_uploads_preserved':len(uploaded),
|
|
'cost_repeats':cost},sort_keys=True))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|