"""Сверка двух stores: dry-run по умолчанию, grace не менее пяти минут.""" import argparse import hashlib import json import time from datetime import timedelta from src.database import Database from src.object_store import ObjectStore from src.settings import integer, secret def verified(store, row, counters): counters["head_requests"] += 1 info = store.head(key=row["object_key"]) if info is None: return "missing" if info.size != row["size_bytes"]: return "mismatch" result = store.get(key=row["object_key"]) digest = hashlib.sha256() size = 0 try: while data := result.read(65536): digest.update(data) size += len(data) counters["bytes_read"] += len(data) if size > 10 * 1024 * 1024: return "mismatch" finally: result.close() result.release_conn() return "valid" if digest.hexdigest() == row["sha256"] else "mismatch" def reconcile(database, store, *, apply, grace): started = time.monotonic() result = { "apply": apply, "grace_seconds": grace, "objects_scanned": 0, "rows_scanned": 0, "head_requests": 0, "bytes_read": 0, "fresh_protected": 0, "ready_protected": 0, "linked_protected": 0, "actions": {}, "applied": {}, "details": [], } with database.connection() as conn: now = conn.execute("SELECT clock_timestamp() AS at").fetchone()["at"] rows = conn.execute("SELECT * FROM attachments ORDER BY id").fetchall() cutoff = now - timedelta(seconds=grace) objects = {o.object_name: o for o in store.objects()} result["objects_scanned"] = len(objects) result["rows_scanned"] = len(rows) keys = {r["object_key"] for r in rows} def record(action, identity, *, changed=False): result["actions"][action] = result["actions"].get(action, 0) + 1 if changed: result["applied"][action] = result["applied"].get(action, 0) + 1 if len(result["details"]) < 20: result["details"].append( {"action": action, "identity": str(identity)} ) for key, obj in objects.items(): if obj.last_modified > cutoff: result["fresh_protected"] += 1 continue if key in keys: continue changed = False if apply: with database.connection() as conn, conn.transaction(): # Fresh intents are checked again immediately before deletion. exists = conn.execute( "SELECT 1 FROM attachments WHERE object_key=%s", (key,) ).fetchone() if exists: continue current = store.head(key=key) result["head_requests"] += 1 if current is not None and current.last_modified > cutoff: result["fresh_protected"] += 1 continue store.delete(key=key) changed = True record("delete_orphan", key, changed=changed) for snapshot in rows: if snapshot["created_at"] > cutoff: continue with database.connection() as conn, conn.transaction(): row = conn.execute( "SELECT * FROM attachments WHERE id=%s FOR UPDATE", (snapshot["id"],), ).fetchone() if row is None or row["created_at"] > cutoff: continue action = None if row["state"] == "pending": state = verified(store, row, result) action = ( "recover_pending" if state == "valid" else "fail_pending_" + state ) if apply: conn.execute( "UPDATE attachments SET state=%s,error_code=%s," "updated_at=clock_timestamp() WHERE id=%s", ( "ready" if state == "valid" else "failed", None if state == "valid" else "upload_" + state, row["id"], ), ) elif row["state"] == "ready": result["head_requests"] += 1 info = store.head(key=row["object_key"]) if info is not None: # A ready attachment stays even if it has no Message link. result["ready_protected"] += 1 continue action = "mark_missing" if apply: conn.execute( "UPDATE attachments SET state='failed'," "error_code='original_missing'," "updated_at=clock_timestamp() WHERE id=%s", (row["id"],), ) else: linked = conn.execute( "SELECT 1 FROM message_attachments " "WHERE attachment_id=%s LIMIT 1", (row["id"],), ).fetchone() if linked: result["linked_protected"] += 1 continue obj = objects.get(row["object_key"]) if obj is None or obj.last_modified > cutoff: continue action = "delete_failed_object" if apply: # A timed-out uploader may finish PUT after LIST. # Recheck freshness before removing its object. current = store.head(key=row["object_key"]) result["head_requests"] += 1 if current is not None and current.last_modified > cutoff: result["fresh_protected"] += 1 continue store.delete(key=row["object_key"]) if action: record(action, row["id"], changed=apply) result["duration_seconds"] = round(time.monotonic() - started, 6) result["complete"] = True return result def main(): parser = argparse.ArgumentParser() parser.add_argument("--apply", action="store_true") parser.add_argument("--loop", action="store_true") args = parser.parse_args() grace = integer("RECONCILE_GRACE_SECONDS", 300, 300, 604800) database = Database(url=secret("DATABASE_URL"), size=2) store = ObjectStore() try: database.open() while True: try: result = reconcile( database, store, apply=args.apply, grace=grace ) print(json.dumps(result, ensure_ascii=False), flush=True) except Exception as exc: print( json.dumps( {"complete": False, "error": type(exc).__name__} ), flush=True, ) if not args.loop: raise SystemExit(1) from None if not args.loop: break time.sleep(60) finally: store.close() database.close() if __name__ == "__main__": main()