"""lab4, уровень 4: компенсация сбоев между S3 и PostgreSQL, grace period, обрыв загрузки. make orphan-cleanup (= python student-tests/orphan_cleanup.py) Внутри контейнера API создаются ровно те состояния, которые остаются после сбоев (attachments.py): - stale: pending-строка часовой давности + объект в S3 = «PUT прошёл, COMMIT ready не прошёл» (БД упала или реплику убили между шагами 4 и 5); - fresh: pending-строка «прямо сейчас» + объект = загрузка, которая идёт в эту секунду; - orphan: объект без строки = строка потеряна, объект остался. Затем уборщик (python -m messenger.cleanup) запускается так: 1. --dry-run: всё найдено, ничего не удалено; 2. обычный запуск (grace 900 с): удалены только stale (объект, потом строка); fresh и orphan моложе grace и не тронуты; готовое вложение на месте; 3. повторный запуск: делать нечего (идемпотентность); 4. --grace-seconds 2 через 3 с (только для теста): удалены и fresh, и orphan; готовое вложение на месте. Отдельно: клиент обрывает загрузку на трети файла — ни строки, ни объекта не появляется. """ import hashlib import json import time import uuid from filegen import cleanup_cli, in_api, png, psql, raw_upload, upload_when_ready from helpers import Client, check, idempotency, run INJECT = """ import io, json, uuid, psycopg from messenger import config, objects chat, user = "{chat}", "{user}" made = {{}} with psycopg.connect(config.DATABASE_URL, autocommit=True) as db: for name, age in (("stale", "1 hour"), ("fresh", "0 seconds")): key = objects.new_key() objects.put(key, io.BytesIO(b"x" * 100), 100, "image/png", "0" * 64) db.execute("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256," " width, height, storage_key, status, created_at) VALUES (%s, %s, %s, 'injected.png'," " 'image/png', 100, %s, 1, 1, %s, 'pending', now() - %s::interval)", (uuid.uuid4(), chat, user, "0" * 64, key, age)) made[name] = key key = objects.new_key() objects.put(key, io.BytesIO(b"y" * 10), 10, "image/png", "1" * 64) made["orphan"] = key print(json.dumps(made)) """ EXISTS = """ import json from messenger import objects keys = {{key for key, _ in objects.list_objects()}} print(json.dumps({{name: key in keys for name, key in json.loads('{keys}').items()}})) """ def exists(keys: dict) -> dict: return json.loads(in_api(EXISTS.format(keys=json.dumps(keys)))) def main(): api = Client() alice, bob, _eve, chat = api.bootstrap() ready = upload_when_ready(api, alice, chat, name="keep.png")["json"] api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice, headers=idempotency(), body={"text": "", "attachment_ids": [ready["id"]]}) keys = json.loads(in_api(INJECT.format(chat=uuid.UUID(chat["id"]), user=uuid.UUID(alice["id"])))) keys["ready"] = psql(f"SELECT storage_key FROM attachments WHERE id = '{uuid.UUID(ready['id'])}'") print("injected: stale pending row + object (PUT ok, COMMIT failed), fresh pending row + object " "(upload in progress), orphan object without a row; plus one ready attachment") def still_ready(): got = api.call("GET", f"/api/v1/attachments/{ready['id']}/content", actor=bob)["bytes"] return hashlib.sha256(got).hexdigest() == ready["sha256"] dry = cleanup_cli("--dry-run") print("1. dry-run:", json.dumps(dry)) check(dry["stale_pending"] >= 1 and dry["pending_deleted"] == 0 and dry["orphans_deleted"] == 0, "dry-run deleted") check(all(exists(keys).values()), "dry-run removed an object") real = cleanup_cli() print("2. cleanup, grace 900 s:", json.dumps(real)) state = exists(keys) check(not state["stale"], "stale object was not removed") check(state["fresh"] and state["orphan"] and state["ready"], "a fresh or ready object was removed") check(psql(f"SELECT count(*) FROM attachments WHERE storage_key = '{keys['stale']}'") == "0", "stale row left") check(still_ready(), "ready attachment changed") print(" stale object and row removed; fresh pending, fresh orphan and the ready attachment kept") again = cleanup_cli() print("3. repeated run:", json.dumps(again)) check(again["pending_deleted"] == 0 and again["orphans_deleted"] == 0, "repeated run is not a no-op") time.sleep(3) short = cleanup_cli("--grace-seconds", "2") print("4. cleanup, grace 2 s (test only):", json.dumps(short)) state = exists(keys) check(not state["fresh"] and not state["orphan"] and state["ready"], "grace 2 s: wrong objects removed") check(still_ready(), "ready attachment changed") print(" after the grace period the old pending upload and the orphan object are removed too; " "the ready attachment is never touched") rows_before = psql(f"SELECT count(*) FROM attachments WHERE chat_id = '{uuid.UUID(chat['id'])}'") objects_before = cleanup_cli("--dry-run")["objects_in_bucket"] data = png(1000, 800, noise=True) raw_upload(f"/api/v1/chats/{chat['id']}/attachments?filename=abort.png", alice["token"], data, abort_after=len(data) // 3) time.sleep(2) rows_after = psql(f"SELECT count(*) FROM attachments WHERE chat_id = '{uuid.UUID(chat['id'])}'") objects_after = cleanup_cli("--dry-run")["objects_in_bucket"] print(f"5. client aborted an upload after {len(data) // 3} of {len(data)} bytes: rows in chat " f"{rows_before} -> {rows_after}, objects in bucket {objects_before} -> {objects_after}") check(rows_before == rows_after and objects_before == objects_after, "aborted upload left something behind") print("PASS: failures between S3 and PostgreSQL leave no permanent unaccounted objects; the grace period " "protects uploads in progress; dry-run and repeated runs are safe; an aborted upload stores nothing") if __name__ == "__main__": run(main)