Добавить приватное S3-хранилище, вложения, presigned upload, reconciler и доказательства.
137 lines
4.9 KiB
Python
137 lines
4.9 KiB
Python
"""Safe, repeatable S3/PostgreSQL reconciler (lab4 operational backstop).
|
|
|
|
What it does
|
|
------------
|
|
* finds S3 objects with no attachment row ("orphans") and deletes only those
|
|
older than a grace period;
|
|
* finds pending presigned uploads older than a grace period and removes both
|
|
the row and any object, so an interrupted direct upload cannot leak forever;
|
|
* reports ready rows whose object is missing and records ``missing_since`` for
|
|
operators without deleting user-visible metadata.
|
|
|
|
``--dry-run`` is the default. ``--apply`` performs the deletions. Re-running
|
|
after an interruption is safe: every action is idempotent.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import logging
|
|
import sys
|
|
from datetime import datetime, timezone
|
|
|
|
from . import db, s3
|
|
from .config import settings
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
|
log = logging.getLogger("messenger.reconcile")
|
|
|
|
|
|
def _age_seconds(now: datetime, value: datetime | None) -> float | None:
|
|
if value is None:
|
|
return None
|
|
if value.tzinfo is None:
|
|
value = value.replace(tzinfo=timezone.utc)
|
|
return (now - value.astimezone(timezone.utc)).total_seconds()
|
|
|
|
|
|
def run(*, apply: bool, orphan_grace: int, pending_grace: int, prefix: str) -> dict:
|
|
now = datetime.now(timezone.utc)
|
|
db.open_pool(timeout=60.0)
|
|
objects = s3.list_objects(prefix)
|
|
object_keys = {item["key"] for item in objects}
|
|
|
|
with db.pool().connection() as conn:
|
|
rows = conn.execute(
|
|
"SELECT id, object_key, status, created_at, missing_since FROM attachments"
|
|
).fetchall()
|
|
|
|
db_keys = {row["object_key"] for row in rows}
|
|
orphans = [item for item in objects if item["key"] not in db_keys]
|
|
stale_orphans = []
|
|
fresh_orphans = []
|
|
for item in orphans:
|
|
age = _age_seconds(now, item["last_modified"])
|
|
if age is None or age >= orphan_grace:
|
|
stale_orphans.append(item)
|
|
else:
|
|
fresh_orphans.append(item)
|
|
|
|
stale_pending = [
|
|
row
|
|
for row in rows
|
|
if row["status"] == "pending"
|
|
and (_age_seconds(now, row["created_at"]) or 0) >= pending_grace
|
|
]
|
|
missing = [
|
|
row
|
|
for row in rows
|
|
if row["status"] == "ready" and row["object_key"] not in object_keys
|
|
]
|
|
|
|
deleted_orphans = 0
|
|
deleted_pending = 0
|
|
marked_missing = 0
|
|
if apply:
|
|
for item in stale_orphans:
|
|
s3.delete(item["key"])
|
|
deleted_orphans += 1
|
|
for row in stale_pending:
|
|
s3.delete(row["object_key"])
|
|
with db.pool().connection() as conn:
|
|
conn.execute(
|
|
"DELETE FROM attachments WHERE id = %s AND status = 'pending'",
|
|
(row["id"],),
|
|
)
|
|
deleted_pending += 1
|
|
for row in missing:
|
|
if row["missing_since"] is None:
|
|
with db.pool().connection() as conn:
|
|
conn.execute(
|
|
"UPDATE attachments SET missing_since = clock_timestamp() WHERE id = %s",
|
|
(row["id"],),
|
|
)
|
|
marked_missing += 1
|
|
|
|
return {
|
|
"apply": apply,
|
|
"grace_seconds": {"orphan": orphan_grace, "pending": pending_grace},
|
|
"objects": len(objects),
|
|
"metadata_rows": len(rows),
|
|
"orphans_total": len(orphans),
|
|
"orphans_fresh_kept": len(fresh_orphans),
|
|
"orphans_stale_deleted": deleted_orphans if apply else len(stale_orphans),
|
|
"stale_pending_deleted": deleted_pending if apply else len(stale_pending),
|
|
"missing_objects_reported": len(missing),
|
|
"missing_objects_marked": marked_missing,
|
|
"sample_orphan_keys": [item["key"] for item in stale_orphans[:5]],
|
|
"sample_missing_keys": [row["object_key"] for row in missing[:5]],
|
|
}
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Reconcile private S3 objects with attachment metadata")
|
|
parser.add_argument("--apply", action="store_true", help="delete stale orphans/pending rows (default: dry-run)")
|
|
parser.add_argument("--dry-run", action="store_true", help="explicit dry-run (default)")
|
|
parser.add_argument("--orphan-grace-seconds", type=int, default=settings.orphan_grace_seconds)
|
|
parser.add_argument("--pending-grace-seconds", type=int, default=settings.presign_grace_seconds)
|
|
parser.add_argument("--prefix", default="")
|
|
args = parser.parse_args()
|
|
apply = args.apply and not args.dry_run
|
|
try:
|
|
summary = run(
|
|
apply=apply,
|
|
orphan_grace=max(0, args.orphan_grace_seconds),
|
|
pending_grace=max(0, args.pending_grace_seconds),
|
|
prefix=args.prefix,
|
|
)
|
|
except s3.S3Unavailable as error:
|
|
log.error("object store is unavailable: %s", type(error).__name__)
|
|
return 2
|
|
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|