205 lines
7.7 KiB
Python
205 lines
7.7 KiB
Python
"""Сверка PostgreSQL и S3: staging, orphans и missing ready.
|
|
|
|
Запуск идемпотентен и по умолчанию только показывает план (`--dry-run`).
|
|
Правила:
|
|
- staging текущей (queued/processing) работы не удаляется никогда;
|
|
- staging ready/failed-вложения удаляется только после retention;
|
|
- variant-объекты ready-вложения считаются используемыми;
|
|
- ready-вложение с пропавшим оригиналом только репортится, metadata не теряется.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
from dataclasses import asdict, dataclass
|
|
from datetime import datetime, timedelta
|
|
from uuid import UUID
|
|
|
|
from .config import Config
|
|
from .db import Database
|
|
from .domain import AttachmentRecord, utc_now
|
|
from .repository import Repository
|
|
from .storage import ObjectInfo, S3Storage, StorageUnavailable
|
|
|
|
logger = logging.getLogger("messenger.reconcile")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PlanItem:
|
|
kind: str
|
|
identifier: str
|
|
object_key: str | None
|
|
age_seconds: int | None
|
|
action: str
|
|
|
|
|
|
def build_plan(
|
|
rows: list[AttachmentRecord],
|
|
objects: list[ObjectInfo],
|
|
*,
|
|
variant_keys: set[str],
|
|
now: datetime,
|
|
grace_seconds: int,
|
|
) -> tuple[list[PlanItem], list[PlanItem]]:
|
|
objects_by_key = {item.key: item for item in objects}
|
|
cutoff = now - timedelta(seconds=grace_seconds)
|
|
items: list[PlanItem] = []
|
|
protected: set[str] = set(variant_keys)
|
|
failed_rows: dict[str, AttachmentRecord] = {}
|
|
|
|
for row in rows:
|
|
if row.status == "ready":
|
|
protected.add(row.object_key)
|
|
elif row.status in ("queued", "processing"):
|
|
protected.add(row.staging_key)
|
|
elif row.status == "failed":
|
|
failed_rows[row.staging_key] = row
|
|
|
|
for item in objects:
|
|
if item.key in protected:
|
|
continue
|
|
row = failed_rows.get(item.key)
|
|
if row is not None:
|
|
age = max(0, int((now - item.last_modified).total_seconds()))
|
|
stale = row.updated_at < cutoff and item.last_modified < cutoff
|
|
items.append(
|
|
PlanItem(
|
|
kind="stale_failed",
|
|
identifier=str(row.id),
|
|
object_key=item.key,
|
|
age_seconds=age,
|
|
action="delete_object_and_row" if stale else "keep_fresh",
|
|
)
|
|
)
|
|
continue
|
|
age = max(0, int((now - item.last_modified).total_seconds()))
|
|
items.append(
|
|
PlanItem(
|
|
kind="orphan_object",
|
|
identifier=item.key,
|
|
object_key=item.key,
|
|
age_seconds=age,
|
|
action="keep_fresh" if item.last_modified >= cutoff else "delete",
|
|
)
|
|
)
|
|
|
|
# ready-объект отсутствует: это авария хранилища, metadata не удаляем.
|
|
missing = [
|
|
PlanItem(
|
|
kind="missing_ready",
|
|
identifier=str(row.id),
|
|
object_key=row.object_key,
|
|
age_seconds=max(0, int((now - row.updated_at).total_seconds())),
|
|
action="report_only",
|
|
)
|
|
for row in rows
|
|
if row.status == "ready" and row.object_key not in objects_by_key
|
|
]
|
|
# failed-строка без staging: удалять нечего, но metadata старше retention
|
|
# остаётся доступной оператору (replay/аудит).
|
|
return items, missing
|
|
|
|
|
|
async def run(args: argparse.Namespace) -> int:
|
|
config = Config.from_env()
|
|
database = Database(config)
|
|
storage = S3Storage(config)
|
|
grace = config.staging_retention_seconds if args.grace_seconds is None else args.grace_seconds
|
|
if grace < 0:
|
|
raise SystemExit("--grace-seconds must be >= 0")
|
|
try:
|
|
async with database.session() as session:
|
|
repository = Repository(session)
|
|
rows = await repository.list_attachment_states()
|
|
variant_keys = await repository.list_variant_keys()
|
|
objects = await storage.list_objects()
|
|
now = utc_now()
|
|
items, missing = build_plan(
|
|
rows,
|
|
objects,
|
|
variant_keys=variant_keys,
|
|
now=now,
|
|
grace_seconds=grace,
|
|
)
|
|
deletable = [
|
|
item
|
|
for item in items
|
|
if item.action in ("delete", "delete_object_and_row")
|
|
]
|
|
summary = {
|
|
"mode": "apply" if args.apply else "dry-run",
|
|
"grace_seconds": grace,
|
|
"prefix": config.s3_key_prefix,
|
|
"metadata_rows": len(rows),
|
|
"variant_keys": len(variant_keys),
|
|
"objects": len(objects),
|
|
"plan": [asdict(item) for item in items],
|
|
"missing_ready": [asdict(item) for item in missing],
|
|
"would_delete_objects": len(
|
|
[item for item in items if item.action in ("delete", "delete_object_and_row")]
|
|
),
|
|
"would_delete_rows": len(
|
|
[item for item in items if item.action == "delete_object_and_row"]
|
|
),
|
|
}
|
|
if not args.apply:
|
|
print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True))
|
|
return 1 if (missing and args.fail_on_missing) else 0
|
|
|
|
deleted_objects = 0
|
|
deleted_rows = 0
|
|
async with database.session() as session:
|
|
repository = Repository(session)
|
|
for item in deletable:
|
|
if item.object_key:
|
|
try:
|
|
await storage.delete(item.object_key)
|
|
deleted_objects += 1
|
|
except StorageUnavailable:
|
|
logger.warning(
|
|
"reconcile_object_delete_failed",
|
|
extra={"fields": {"key": item.object_key}},
|
|
)
|
|
continue
|
|
if item.action == "delete_object_and_row":
|
|
try:
|
|
if await repository.delete_attachment_if_stale(
|
|
UUID(item.identifier), now - timedelta(seconds=grace)
|
|
):
|
|
deleted_rows += 1
|
|
except Exception:
|
|
logger.warning(
|
|
"reconcile_row_delete_failed",
|
|
extra={"fields": {"id": item.identifier}},
|
|
)
|
|
summary["deleted_objects"] = deleted_objects
|
|
summary["deleted_rows"] = deleted_rows
|
|
print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True))
|
|
return 1 if (missing and args.fail_on_missing) else 0
|
|
finally:
|
|
await storage.close()
|
|
await database.dispose()
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description="Сверка вложений PostgreSQL и S3")
|
|
parser.add_argument("--apply", action="store_true", help="действительно удалять мусор")
|
|
parser.add_argument("--dry-run", action="store_true", help="только показать план (по умолчанию)")
|
|
parser.add_argument(
|
|
"--grace-seconds",
|
|
type=int,
|
|
default=None,
|
|
help="возраст, после которого staging failed/ready удаляется",
|
|
)
|
|
parser.add_argument("--fail-on-missing", action="store_true", help="код 1, если ready-объект отсутствует")
|
|
args = parser.parse_args(argv)
|
|
if args.dry_run:
|
|
args.apply = False
|
|
return asyncio.run(run(args))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|