import base64 from collections import Counter from datetime import datetime, timedelta, timezone import hashlib import json from pathlib import Path import re import sys import time import boto3 from botocore.config import Config from botocore.exceptions import ClientError import psycopg from psycopg.rows import dict_row MAX_BYTES = 10 * 1024 * 1024 class Reconciler: def __init__(self, config): self.config = config self.started = time.monotonic() self.cutoff = ( datetime.now(timezone.utc) - timedelta(seconds=config["grace_seconds"]) ) self.counts = Counter() self.sql_calls = 0 self.s3_calls = Counter() self.examples = [] self.db = None self.s3 = boto3.client( "s3", **config["s3"], config=Config( signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=3, read_timeout=15, retries={"total_max_attempts": 1}, ), ) def sql(self, statement, params=()): self.sql_calls += 1 return self.db.execute(statement, params) def call(self, operation, **kwargs): self.s3_calls[operation] += 1 return getattr(self.s3, operation)( Bucket=self.config["bucket"], **kwargs, ) def event(self, name, key=None): self.counts[name] += 1 # Ограничиваем размер подробной части отчёта. if key is not None and len(self.examples) < 100: self.examples.append({ "outcome": name, "object_key": key, }) def deadline(self): elapsed = time.monotonic() - self.started if elapsed > self.config["max_seconds"]: raise TimeoutError("Scan deadline reached") def lock(self, key): # Тот же ключ блокировки, что используется # AttachmentRepository в Java. row = self.sql( """ SELECT pg_try_advisory_xact_lock( hashtextextended(%s, 0) ) AS ok """, ("attachment-object:" + key,), ).fetchone() if not row["ok"]: self.event("busy", key) return row["ok"] def head(self, key): try: return self.call("head_object", Key=key) except ClientError as error: code = error.response.get("Error", {}).get("Code", "") if code not in ( "404", "NoSuchKey", "NoSuchObject", "NotFound", ): raise # Проверяем, что доступен сам bucket. # Исчезновение bucket не считаем потерей # отдельного оригинала. self.call("head_bucket") return None def scan_objects(self): token = None chat_id = self.config.get("chat_id") prefix = ( f"originals/{chat_id}/" if chat_id else "originals/" ) while True: self.deadline() args = { "Prefix": prefix, "MaxKeys": 500, } if token: args["ContinuationToken"] = token page = self.call("list_objects_v2", **args) for item in page.get("Contents", []): self.deadline() self.event("objects_scanned") key = item["Key"] if item["LastModified"] >= self.cutoff: self.event("fresh_objects") continue with self.db.transaction(): if not self.lock(key): continue # Проверяем всю таблицу, даже если проход # ограничен одним тестовым чатом. row = self.sql( """ SELECT id FROM attachments WHERE object_key = %s """, (key,), ).fetchone() if row: self.event("referenced_objects") continue # Повторная проверка после блокировки. current = self.head(key) if current is None: self.event("already_absent") elif current["LastModified"] >= self.cutoff: self.event("fresh_objects") elif self.config["apply"]: self.call("delete_object", Key=key) self.event("deleted_orphans", key) else: self.event("would_delete_orphans", key) if not page.get("IsTruncated"): break token = page["NextContinuationToken"] def backup(self, row): checksum = row["sha256"].strip() if not re.fullmatch("[a-f0-9]{64}", checksum): raise ValueError("Invalid metadata checksum") # Имя копии определяется SHA-256, а не filename. path = Path("/backups") / (checksum + ".bin") if not path.exists(): return None # Ограничиваем чтение даже для ошибочной копии. with path.open("rb") as stream: data = stream.read(MAX_BYTES + 1) valid = ( len(data) == row["size_bytes"] and hashlib.sha256(data).hexdigest() == checksum ) if not valid: self.event("invalid_backups", row["object_key"]) return None return data def check_attachment(self, attachment_id): # В текущем протоколе object_key неизменяем. initial = self.sql( """ SELECT object_key FROM attachments WHERE id = %s """, (attachment_id,), ).fetchone() if not initial: return key = initial["object_key"] with self.db.transaction(): if not self.lock(key): return row = self.sql( """ SELECT * FROM attachments WHERE id = %s FOR SHARE """, (attachment_id,), ).fetchone() if not row: return if ( row["object_key"] != key or not key.startswith("originals/") ): raise ValueError("Unsupported object key") if row["created_at"] >= self.cutoff: self.event("fresh_metadata") return current = self.head(key) if current is not None: if current["ContentLength"] == row["size_bytes"]: self.event("present_metadata") else: self.event("size_mismatches", key) return self.event("missing_objects", key) data = self.backup(row) if data is None: # Метаданные и сообщения сохраняем. self.event("unresolved_missing", key) return if not self.config["apply"]: self.event("would_restore", key) return # Восстанавливаем отсутствующий объект, # удерживая ту же блокировку, что и API. self.call( "put_object", Key=key, Body=data, ContentType=row["content_type"], ContentMD5=base64.b64encode( hashlib.md5(data).digest() ).decode("ascii"), ) # Проверяем фактические байты после записи. response = self.call("get_object", Key=key) with response["Body"] as stream: actual = stream.read(MAX_BYTES + 1) valid = ( len(actual) == row["size_bytes"] and hashlib.sha256(actual).hexdigest() == row["sha256"].strip() ) if not valid: raise ValueError( "Restored object verification failed" ) self.event("restored", key) def scan_metadata(self): cursor = None chat_id = self.config.get("chat_id") while True: self.deadline() rows = self.sql( """ SELECT id FROM attachments WHERE ( %s::uuid IS NULL OR chat_id = %s::uuid ) AND ( %s::uuid IS NULL OR id > %s::uuid ) ORDER BY id LIMIT 500 """, (chat_id, chat_id, cursor, cursor), ).fetchall() if not rows: return for row in rows: self.deadline() self.event("metadata_scanned") self.check_attachment(row["id"]) cursor = rows[-1]["id"] def run(self): status = "completed" error_type = None try: with psycopg.connect( **self.config["db"], autocommit=True, row_factory=dict_row, connect_timeout=5, options=( "-c statement_timeout=10000 " "-c idle_in_transaction_session_timeout=120000" ), ) as db: self.db = db # Только один полный проход этой утилиты # одновременно в данной БД. locked = self.sql( """ SELECT pg_try_advisory_lock( hashtextextended( 'attachment-reconciler:v1', 0 ) ) AS ok """ ).fetchone()["ok"] if not locked: raise RuntimeError( "Another reconciler is running" ) self.call("head_bucket") self.scan_objects() self.scan_metadata() # Закрытие соединения освобождает session lock. # Блокировки объектов освобождаются # при завершении отдельных транзакций. except Exception as error: status = "failed" error_type = type(error).__name__ finally: self.s3.close() attention_counters = ( "unresolved_missing", "size_mismatches", "invalid_backups", "busy", ) if status == "completed" and any( self.counts[name] for name in attention_counters ): status = "needs_attention" report = { "status": status, "mode": ( "apply" if self.config["apply"] else "dry-run" ), "chat_id": self.config.get("chat_id"), "cutoff": self.cutoff.isoformat(), "elapsed_seconds": round( time.monotonic() - self.started, 3, ), "counts": dict(self.counts), "sql_statement_calls": self.sql_calls, "s3_operation_calls": dict(self.s3_calls), "examples": self.examples, "examples_limit": 100, "error_type": error_type, } print(json.dumps( report, ensure_ascii=False, indent=2, )) return { "completed": 0, "needs_attention": 2, "failed": 1, }[status] if __name__ == "__main__": config = json.load(sys.stdin) if ( config["grace_seconds"] < 60 or config["max_seconds"] < 1 ): raise SystemExit("Invalid scan limits") raise SystemExit(Reconciler(config).run())