Files
mtusi2026lab4/scripts/test_s3_db_compensation.py

128 lines
3.4 KiB
Python

import sys
from pathlib import Path
from sqlalchemy import text
ROOT = Path("/app")
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check
from app.core.config import settings
from app.db.models import Attachment
from app.db.session import SessionLocal
from app.services.object_storage import client as s3_client
TRIGGER_NAME = "lab4_force_attachment_insert_failure"
FUNCTION_NAME = "lab4_fail_attachment_insert"
TEST_FILENAME = "lab4-forced-db-failure.png"
def install_failure_trigger():
table = Attachment.__table__
schema = table.schema or "public"
qualified_table = f'"{schema}"."{table.name}"'
with SessionLocal() as db:
db.execute(text(f"""
CREATE OR REPLACE FUNCTION public.{FUNCTION_NAME}()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF NEW.filename = '{TEST_FILENAME}' THEN
RAISE EXCEPTION 'Lab 4 controlled metadata failure'
USING ERRCODE = 'P0001';
END IF;
RETURN NEW;
END;
$$;
"""))
db.execute(text(
f'DROP TRIGGER IF EXISTS {TRIGGER_NAME} ON {qualified_table}'
))
db.execute(text(
f'CREATE TRIGGER {TRIGGER_NAME} '
f'BEFORE INSERT ON {qualified_table} '
f'FOR EACH ROW EXECUTE FUNCTION public.{FUNCTION_NAME}()'
))
db.commit()
def remove_failure_trigger():
table = Attachment.__table__
schema = table.schema or "public"
qualified_table = f'"{schema}"."{table.name}"'
with SessionLocal() as db:
db.execute(text(
f'DROP TRIGGER IF EXISTS {TRIGGER_NAME} ON {qualified_table}'
))
db.execute(text(
f'DROP FUNCTION IF EXISTS public.{FUNCTION_NAME}()'
))
db.commit()
def object_keys(s3, prefix):
result = s3.list_objects_v2(
Bucket=settings.s3_bucket,
Prefix=prefix,
)
return {
item["Key"]
for item in result.get("Contents", [])
}
def main():
client = Client("http://127.0.0.1:8080")
alice, bob, eve, chat = client.bootstrap()
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
prefix = f"original/{chat['id']}/"
s3 = s3_client()
before = object_keys(s3, prefix)
install_failure_trigger()
print("Temporary PostgreSQL failure trigger installed.")
try:
response = client.call(
"POST",
f"/api/v1/chats/{chat['id']}/attachments"
f"?filename={TEST_FILENAME}",
expected=503,
actor=alice,
raw=content,
headers={"Content-Type": "image/png"},
)
check(
response["status"] == 503,
"Expected HTTP 503 after forced metadata failure",
)
print("PASS: S3 upload succeeded, PostgreSQL metadata insert failed")
after = object_keys(s3, prefix)
unexpected_objects = after - before
check(
not unexpected_objects,
"Compensation failed: unexpected S3 objects remain",
)
print("PASS: uploaded S3 object was deleted after DB failure")
print()
print("PASS: S3/PostgreSQL compensation scenario")
finally:
remove_failure_trigger()
print("Temporary PostgreSQL trigger removed.")
if __name__ == "__main__":
main()