Files
mtusi2026lab6/student-tests/reconcile_audit.py
T
2026-11-05 21:17:50 +03:00

160 lines
7.6 KiB
Python

#!/usr/bin/env python3
"""Real database rejection, concurrent commit, interrupted upload and pagination."""
import base64
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, run
PROBE = r'''
import asyncio, base64, hashlib, http.client, json, sys, urllib.request, urllib.error
from types import SimpleNamespace
from uuid import UUID, uuid4
from src.config import load_settings
from src.storage.postgres import PostgresStore
from src.storage.s3 import S3Store, S3Settings
from src.reconcile import run as reconcile, scan
payload = json.load(sys.stdin)
image = base64.b64decode(payload['image'])
chat_id, user_id = UUID(payload['chat_id']), UUID(payload['user_id'])
def upload(filename):
req = urllib.request.Request('http://api-a:8080/api/v1/chats/' + str(chat_id) +
'/attachments?filename=' + filename, data=image, method='POST',
headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
try:
with urllib.request.urlopen(req, timeout=30) as response:
return response.status, json.load(response)
except urllib.error.HTTPError as error:
return error.code, json.load(error)
async def main():
db = PostgresStore(load_settings().database_url)
s3 = S3Store(S3Settings.load())
await db.connect()
def args(key):
return SimpleNamespace(apply=True, grace_seconds=0, object_key=[key])
try:
# A failed metadata inventory must not authorize any S3 deletion.
key = 'originals/audit-inventory-' + uuid4().hex
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
class BrokenInventory:
async def attachment_keys(self):
# Real SQL failure, not an empty inventory on error.
return await db.pool.fetch('SELECT * FROM audit_missing_table_' + uuid4().hex)
try:
async with db.attachment_transaction(maintenance=True):
try:
await scan(args(key), BrokenInventory(), s3)
except Exception:
pass
else:
raise AssertionError('failed inventory did not abort')
assert key in await s3.list('originals/')
finally:
await s3.delete(key)
print('PASS: failed PostgreSQL inventory aborts apply without deleting the orphan', flush=True)
# An actual PostgreSQL trigger rejects only this test chat's INSERT.
suffix = uuid4().hex
name = 'audit_reject_' + suffix
before = await s3.list('originals/')
await db.pool.execute(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN IF NEW.chat_id = '{chat_id}'::uuid THEN
RAISE EXCEPTION 'synthetic audit rejection' USING ERRCODE = '23514';
END IF; RETURN NEW; END $$""")
try:
await db.pool.execute(f'CREATE TRIGGER {name} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {name}()')
status, body = await asyncio.to_thread(upload, 'db-failure.png')
assert status == 503 and body['error']['code'] == 'unavailable', (status, body)
assert await db.pool.fetchval('SELECT count(*) FROM attachments WHERE chat_id=$1', chat_id) == 0
finally:
await db.pool.execute(f'DROP TRIGGER IF EXISTS {name} ON attachments')
await db.pool.execute(f'DROP FUNCTION {name}()')
created = set(await s3.list('originals/')) - set(before)
assert len(created) == 1, created
key = created.pop()
report = await reconcile(SimpleNamespace(apply=False, grace_seconds=0, object_key=[key]))
assert key in report['orphan_candidates'] and not report['deleted']
assert (await reconcile(args(key)))['deleted'] == [key]
assert not (await reconcile(args(key)))['deleted']
print('PASS: actual PostgreSQL INSERT rejection -> 503, dry-run detection, scoped repair, repeat no-op', flush=True)
# Writer holds a shared lock after PUT; cleanup must wait for COMMIT.
identifier = uuid4()
key = 'originals/' + str(identifier)
async with db.attachment_transaction() as connection:
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
sweep = asyncio.create_task(reconcile(args(key)))
for _ in range(40):
waiting = await db.pool.fetchval("SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=41004 AND objid=1 AND NOT granted")
if waiting:
break
await asyncio.sleep(.05)
assert waiting and not sweep.done(), 'maintenance failed to wait for active writer'
await db.create_attachment(identifier, chat_id, user_id, 'concurrent.png', 'image/png',
len(image), hashlib.sha256(image).hexdigest(), key, connection=connection)
report = await sweep
assert key not in report['deleted'] and key not in report['orphan_candidates']
row = await db.attachment_for_member(identifier, user_id)
assert await s3.download(row) == image
print('PASS: apply with zero grace waits for in-flight PUT/COMMIT; committed original survives', flush=True)
# Abrupt client close before all bytes arrive must not persist a file.
before = await s3.list('originals/')
rows = await db.attachment_keys()
def interrupt():
conn = http.client.HTTPConnection('api-a', 8080, timeout=10)
conn.putrequest('POST', '/api/v1/chats/' + str(chat_id) + '/attachments?filename=interrupted.png')
conn.putheader('Authorization', 'Bearer ' + payload['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(len(image) + 100000))
conn.endheaders()
conn.send(image[:32])
conn.close()
await asyncio.to_thread(interrupt)
await asyncio.sleep(1)
assert await db.attachment_keys() == rows
assert await s3.list('originals/') == before
status, body = await asyncio.to_thread(upload, 'after-disconnect.png')
assert status == 201, (status, body)
print('PASS: interrupted upload leaves no metadata/object and next upload succeeds', flush=True)
# Exercise pagination on real S3 without adding thousands of fixtures.
original_call = s3.call
async def small_pages(method, **kwargs):
if method == 'list_objects_v2':
kwargs['MaxKeys'] = 7
return await original_call(method, **kwargs)
expected = await s3.list('originals/')
s3.call = small_pages
actual, pages = await s3.list_with_pages('originals/')
assert actual == expected and pages > 1
print(f'PASS: S3 pagination: {len(actual)} keys across {pages} pages, no missing/duplicate keys', flush=True)
finally:
s3.client.close()
await db.close()
asyncio.run(main())
'''
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=30)
alice, _, _, chat = client.bootstrap()
payload = {"chat_id": chat["id"], "user_id": alice["id"], "token": alice["token"],
"image": base64.b64encode((ROOT / "tests/fixtures/sample.png").read_bytes()).decode()}
subprocess.run(["docker", "compose", "--profile", "maintenance", "run", "--rm", "--no-deps",
"--entrypoint", "/app/.venv/bin/python", "reconcile", "-c", PROBE],
cwd=ROOT, input=json.dumps(payload), text=True, check=True)
if __name__ == "__main__":
run(main)