from __future__ import annotations import asyncio import hashlib import time from uuid import uuid4 from botocore.exceptions import ClientError import psycopg import app.cleanup_orphans as cleanup from app.object_locks import object_lock_id from app.storage import bucket_name, get_client, get_object client = get_client() bucket = bucket_name() with cleanup.database_connection() as conn: original = conn.execute( """ SELECT object_key, chat_id, owner_id, sha256 FROM attachments ORDER BY created_at, id LIMIT 1 """ ).fetchone() if original is None: raise SystemExit("Нужно существующее корректное вложение") orphan_id = uuid4() orphan_key = f"originals/{orphan_id}" busy_key = f"originals/{uuid4()}" fresh_key = f"originals/{uuid4()}" test_keys = {orphan_key, busy_key, fresh_key} scope = test_keys | {original["object_key"]} body = b"controlled-orphan-test" class ScopedPages: def paginate(self, **kwargs): paginator = client.get_paginator("list_objects_v2") for page in paginator.paginate(**kwargs): yield { **page, "Contents": [ item for item in page.get("Contents", []) if item["Key"] in scope ], } class ScopedClient: def get_paginator(self, name): assert name == "list_objects_v2" return ScopedPages() def __getattr__(self, name): return getattr(client, name) cleanup.get_client = lambda: ScopedClient() def sweep(apply): result = cleanup.sweep(apply=apply, grace_seconds=60) print(result, flush=True) return result def exists(key): try: client.head_object(Bucket=bucket, Key=key) return True except ClientError as exc: status = exc.response.get( "ResponseMetadata", {} ).get("HTTPStatusCode") if status == 404: return False raise try: client.put_object( Bucket=bucket, Key=orphan_key, Body=body, ContentType="application/octet-stream", ) with cleanup.database_connection() as conn: with conn.transaction(): conn.execute( """ INSERT INTO attachments ( id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) """, ( orphan_id, original["chat_id"], original["owner_id"], "rollback-test.png", "image/png", len(body), hashlib.sha256(body).hexdigest(), orphan_key, ), ) raise psycopg.Rollback() row = conn.execute( "SELECT 1 FROM attachments WHERE object_key = %s", (orphan_key,), ).fetchone() assert row is None assert exists(orphan_key) print("OK: S3 PUT сохранён, метаданные откатились", flush=True) client.put_object( Bucket=bucket, Key=busy_key, Body=body, ) result = sweep(False) assert result["candidates"] == 0 assert result["deleted"] == 0 assert result["fresh"] >= 2 print("OK: свежие orphan-объекты сохранены", flush=True) print("Ждём 65 секунд для тестового grace period...", flush=True) time.sleep(65) client.put_object( Bucket=bucket, Key=fresh_key, Body=body, ) with cleanup.database_connection() as lock_conn: with lock_conn.transaction(): lock_conn.execute( "SET LOCAL " "idle_in_transaction_session_timeout = '180s'" ) lock_conn.execute( "SELECT pg_advisory_xact_lock(%s)", (object_lock_id(bucket, busy_key),), ) result = sweep(False) assert result["candidates"] == 1 assert result["deleted"] == 0 assert result["busy"] == 1 assert result["fresh"] == 1 assert result["kept"] == 1 assert exists(orphan_key) print("OK: dry-run ничего не удалил", flush=True) result = sweep(True) assert result["deleted"] == 1 assert result["busy"] == 1 assert result["fresh"] == 1 assert result["kept"] == 1 assert not exists(orphan_key) assert exists(busy_key) assert exists(fresh_key) print("OK: удалён только старый незанятый orphan", flush=True) result = sweep(True) assert result["deleted"] == 0 assert result["candidates"] == 0 print("OK: повторный запуск безопасен", flush=True) result = sweep(True) assert result["deleted"] == 1 assert not exists(busy_key) assert exists(fresh_key) print("OK: после освобождения блокировки orphan очищен", flush=True) downloaded = asyncio.run(get_object(original["object_key"])) assert hashlib.sha256(downloaded).hexdigest() == original["sha256"] print("OK: существующее вложение не повреждено", flush=True) print("PASS: orphan cleanup safety and rollback recovery", flush=True) finally: for key in test_keys: client.delete_object(Bucket=bucket, Key=key) print("Только собственные тестовые объекты убраны", flush=True)