#!/usr/bin/env python3 """Lab4/Lab5 evidence: safe S3/PostgreSQL reconciliation with a grace period.""" from __future__ import annotations import argparse import json import os import subprocess import uuid from pathlib import Path import boto3 from botocore.config import Config from common import HttpClient, assert_status ROOT = Path(__file__).resolve().parents[1] def read_env() -> dict[str, str]: values = dict(os.environ) path = ROOT / ".env" if path.is_file(): for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, value = line.partition("=") values.setdefault(key.strip(), value.strip()) return values def s3_client(env: dict[str, str]): return boto3.client( "s3", endpoint_url=env["S3_PUBLIC_ENDPOINT"], region_name=env.get("S3_REGION", "us-east-1"), aws_access_key_id=env["S3_ACCESS_KEY_ID"], aws_secret_access_key=env["S3_SECRET_ACCESS_KEY"], config=Config(signature_version="s3v4", s3={"addressing_style": "path"}), ) def reconcile(extra: list[str]) -> dict: result = subprocess.run( [ "docker", "compose", "--env-file", ".env", "--profile", "tools", "run", "--rm", "--no-deps", "reconcile", "python", "-m", "app.reconcile", *extra, ], cwd=ROOT, capture_output=True, text=True, timeout=120, ) if result.returncode != 0: raise AssertionError( "reconciler failed: " + (result.stderr or result.stdout)[-500:] ) for line in reversed(result.stdout.splitlines()): line = line.strip() if line.startswith("{"): return json.loads(line) raise AssertionError("reconciler did not print a JSON summary") def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") args = parser.parse_args() env = read_env() client = s3_client(env) bucket = env["S3_BUCKET"] # 1. A fresh orphan is reported by a dry-run and is not deleted. orphan_key = "reconcile-tests/orphan-" + uuid.uuid4().hex client.put_object(Bucket=bucket, Key=orphan_key, Body=b"orphan", ContentType="text/plain") dry = reconcile( ["--dry-run", "--orphan-grace-seconds", "0", "--pending-grace-seconds", "0"] ) if dry["orphans_stale_deleted"] < 1: raise AssertionError("dry-run did not report the injected orphan") client.head_object(Bucket=bucket, Key=orphan_key) # 2. A fresh orphan inside the default grace window is kept by --apply. kept_key = "reconcile-tests/kept-" + uuid.uuid4().hex client.put_object(Bucket=bucket, Key=kept_key, Body=b"kept", ContentType="text/plain") kept = reconcile( ["--apply", "--orphan-grace-seconds", "86400", "--pending-grace-seconds", "86400"] ) if kept["orphans_fresh_kept"] < 1: raise AssertionError("grace-window orphan was not reported as kept") client.head_object(Bucket=bucket, Key=kept_key) # 3. --apply with grace 0 removes both injected objects. applied = reconcile( ["--apply", "--orphan-grace-seconds", "0", "--pending-grace-seconds", "0"] ) if applied["orphans_stale_deleted"] < 2: raise AssertionError("apply did not delete the injected orphans") for key in (orphan_key, kept_key): try: client.head_object(Bucket=bucket, Key=key) except Exception: pass else: raise AssertionError("orphan still exists after apply") # 4. An interrupted presigned upload is removed with its metadata row. http = HttpClient(args.base_url) alice, alice_reg = http.register() token = http.login(alice_reg)["token"] status, _h, chat, _r = http.call( "POST", "/api/v1/chats", body={"title": "Reconcile pending", "member_ids": [alice["id"]]}, token=token, ) assert_status(status, 201, "create chat") import hashlib import io from PIL import Image buffer = io.BytesIO() Image.new("RGB", (32, 32), (10, 20, 30)).save(buffer, format="PNG") png = buffer.getvalue() digest = hashlib.sha256(png).hexdigest() status, _h, pending, _r = http.call( "POST", "/api/v1/chats/" + chat["id"] + "/attachments/presign", body={ "filename": "pending.png", "content_type": "image/png", "size_bytes": len(png), "sha256": digest, }, token=token, ) assert_status(status, 201, "presign pending") pending_summary = reconcile( ["--apply", "--orphan-grace-seconds", "86400", "--pending-grace-seconds", "0"] ) if pending_summary["stale_pending_deleted"] < 1: raise AssertionError("stale pending upload was not removed") status, _h, _p, _r = http.call( "GET", "/api/v1/attachments/" + pending["attachment_id"], token=token ) assert_status(status, 404, "pending metadata removed") print("PASS: dry-run/apply reconciliation, grace period, orphan cleanup, stale pending cleanup") if __name__ == "__main__": main()