from __future__ import annotations import base64 import json import secrets import time from uuid import UUID, uuid4 from queued_restart import ROOT, api, dc, http, wait_ready EVIDENCE = ROOT / "evidence" / "staging_cleanup.json" def storage_action(attachment_id, action): code = """ import json import sys from uuid import UUID from app.job_db import connect_db from app.storage import _get, _put, bucket_name, get_client attachment_id = UUID(sys.argv[1]) action = sys.argv[2] prefix = f"staging/{attachment_id}/" extra = prefix + "v99" client = get_client() bucket = bucket_name() if action == "add_orphan": _put(extra, b"synthetic unreferenced staging object", "image/png") elif action == "remove_orphan": client.delete_object(Bucket=bucket, Key=extra) elif action == "add_ready_leftover": with connect_db() as db: with db.transaction(): row = db.execute( ''' SELECT object_key, content_type, status FROM attachments WHERE id = %s FOR UPDATE ''', (attachment_id,), ).fetchone() if row is None or row["status"] != "ready": raise RuntimeError("Expected a genuinely ready attachment") data = _get(row["object_key"]) staging_key = prefix + "v1" _put(staging_key, data, row["content_type"]) db.execute( "UPDATE attachments SET staging_key = %s WHERE id = %s", (staging_key, attachment_id), ) elif action != "inspect": raise ValueError("Unknown action") keys = [] for page in client.get_paginator("list_objects_v2").paginate( Bucket=bucket, Prefix=prefix, ): keys.extend(item["Key"] for item in page.get("Contents", [])) with connect_db() as db: row = db.execute( ''' SELECT status, staging_key IS NOT NULL AS staging_reference FROM attachments WHERE id = %s ''', (attachment_id,), ).fetchone() print(json.dumps({"keys": sorted(keys), **row})) """ return json.loads( dc( "exec", "-T", "api", "python", "-c", code, attachment_id, action, ) ) def cleanup(attachment_id, *, apply=False): args = [ "exec", "-T", "worker", "python", "-m", "app.cleanup_staging", "--attachment-id", attachment_id, "--grace-seconds", "0", "--allow-short-grace", ] if apply: args.append("--apply") return json.loads(dc(*args)) def main(): evidence = {"scenario": "scoped staging cleanup safety"} attachment_id = None restore = False try: wait_ready() if not dc("ps", "--status", "running", "-q", "worker"): raise AssertionError("Start worker before this test") username = "cln_" + uuid4().hex[:16] password = secrets.token_hex(16) user = api( "POST", "/api/v1/users", 201, payload={ "username": username, "display_name": "Staging cleanup test", "password": password, }, ) basic = base64.b64encode( f"{username}:{password}".encode() ).decode() token = api( "POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + basic}, )["token"] chat = api( "POST", "/api/v1/chats", 201, token=token, payload={ "title": "Staging cleanup", "member_ids": [user["id"]], }, ) restore = True dc("stop", "worker") assert not dc("ps", "--status", "running", "-q", "worker") original = (ROOT / "tests/fixtures/sample.png").read_bytes() attachment = api( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 202, token=token, data=original, headers={"Content-Type": "image/png"}, ) attachment_id = str(UUID(attachment["id"])) path = f"/api/v1/attachments/{attachment_id}" active_key = f"staging/{attachment_id}/v1" orphan_key = f"staging/{attachment_id}/v99" state = storage_action(attachment_id, "add_orphan") assert state["status"] == "queued" assert state["keys"] == sorted([active_key, orphan_key]) # worker остановлен, поэтому уборщик запускаем в API-контейнере. # Модуль и настройки хранилищ у него те же. def scoped_cleanup(apply): args = [ "exec", "-T", "api", "python", "-m", "app.cleanup_staging", "--attachment-id", attachment_id, "--grace-seconds", "0", "--allow-short-grace", ] if apply: args.append("--apply") return json.loads(dc(*args)) dry = scoped_cleanup(False) assert dry["active"] == 1 assert dry["candidates"] == 1 assert dry["deleted"] == 0 assert storage_action(attachment_id, "inspect")["keys"] == state["keys"] applied = scoped_cleanup(True) assert applied["active"] == 1 assert applied["deleted"] == 1 state = storage_action(attachment_id, "inspect") assert state["keys"] == [active_key] assert state["staging_reference"] is True assert api("GET", path, 200, token=token)["status"] == "queued" evidence["queued_dry_run"] = dry evidence["queued_apply"] = applied print("Dry-run preserved both objects; apply removed only the orphan") dc("start", "worker") deadline = time.monotonic() + 90 while time.monotonic() < deadline: ready = api("GET", path, 200, token=token) if ready["status"] == "ready": break if ready["status"] == "failed": raise AssertionError("Active staging was not processed") time.sleep(0.5) else: raise AssertionError("Ready timeout") # Дожидаемся завершения штатной уборки в job_runner. deadline = time.monotonic() + 30 while time.monotonic() < deadline: state = storage_action(attachment_id, "inspect") if not state["keys"] and not state["staging_reference"]: break time.sleep(0.5) else: raise AssertionError("Normal staging cleanup did not finish") # Имитируем остаток после сбоя удаления, не подделывая ready: # оригинал и варианты уже созданы настоящим worker. storage_action(attachment_id, "add_ready_leftover") ready_dry = cleanup(attachment_id) assert ready_dry["candidates"] == 1 assert ready_dry["deleted"] == 0 ready_apply = cleanup(attachment_id, apply=True) assert ready_apply["deleted"] == 1 state = storage_action(attachment_id, "inspect") assert state["status"] == "ready" assert state["keys"] == [] assert state["staging_reference"] is False assert api("GET", path, 200, token=token) == ready status, body = http("GET", path + "/content", token=token) assert status == 200 and body == original for variant in ready["variants"]: status, body = http( "GET", path + "/content?variant=" + variant["name"], token=token, ) assert status == 200 assert len(body) == variant["size_bytes"] evidence["attachment_id"] = attachment_id evidence["ready_dry_run"] = ready_dry evidence["ready_apply"] = ready_apply evidence["final_storage_state"] = state evidence["result"] = "PASS" except BaseException as exc: evidence["result"] = "FAIL" evidence["error_type"] = type(exc).__name__ raise finally: try: if attachment_id is not None: storage_action(attachment_id, "remove_orphan") finally: try: if restore: dc("start", "worker") finally: EVIDENCE.parent.mkdir(exist_ok=True) EVIDENCE.write_text( json.dumps(evidence, ensure_ascii=False, indent=2) + "\n" ) print( "PASS: dry-run is non-destructive; queued staging preserved; " "orphan and ready leftover removed; ready content intact" ) if __name__ == "__main__": main()