Files
mtusi2026lab5/src/app/storage/s3_cleanup.py
T

156 lines
5.1 KiB
Python

"""Фоновая сверка S3 и PostgreSQL (уровень 4 lab4/lab5).
- Orphan: объект в S3 есть, а метаданных/вариантов в БД нет.
Удаляем только если объект старше ORPHAN_GRACE_SECONDS.
- Missing: метаданные есть, объекта в S3 нет — warning.
- Staging: объекты staging/ старше grace удаляются (не привязаны к текущей работе).
- Также периодически возвращает зависшие processing в queued.
"""
import logging
import os
import sys
import time
from datetime import datetime, timedelta, timezone
from . import s3
from .db import connection, init_pool, close_pool
from .postgres import storage
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
stream=sys.stdout,
)
log = logging.getLogger("s3_cleanup")
def _interval() -> int:
try:
return max(30, int(os.environ.get("CLEANUP_INTERVAL_SECONDS", "300")))
except ValueError:
return 300
def _grace() -> int:
try:
return max(0, int(os.environ.get("ORPHAN_GRACE_SECONDS", "3600")))
except ValueError:
return 3600
def _known_keys() -> set[str]:
"""Все ожидаемые object key: оригиналы + варианты."""
keys: set[str] = set()
with connection() as conn, conn.cursor() as cur:
cur.execute("SELECT id, chat_id, object_key FROM attachments")
for aid, cid, okey in cur.fetchall():
keys.add(okey)
keys.add(s3.original_key(cid, aid))
cur.execute("SELECT attachment_id, variant FROM attachment_variants")
# нужен chat_id для variant_key
# variants: отдельным запросом с join
with connection() as conn, conn.cursor() as cur:
cur.execute(
"SELECT a.chat_id, v.attachment_id, v.variant"
" FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id"
)
for cid, aid, variant in cur.fetchall():
keys.add(s3.variant_key(cid, aid, variant))
return keys
def _run_once() -> dict:
now = datetime.now(timezone.utc)
grace_cutoff = now - timedelta(seconds=_grace())
known = _known_keys()
orphan_deleted = 0
missing = 0
scanned = 0
staging_deleted = 0
# attachments/ — orphan по known
for obj in s3.list_objects("attachments/"):
scanned += 1
key = obj["Key"]
if key in known:
continue
# Orphan: в S3 есть, в БД нет. Удаляем только старше grace period.
lm = obj.get("LastModified")
if lm is None:
continue
if lm.tzinfo is None:
lm = lm.replace(tzinfo=timezone.utc)
if lm > grace_cutoff:
# Свежий объект — возможно in-flight upload; не трогаем.
continue
try:
s3.delete_object(key)
orphan_deleted += 1
log.info("event=orphan_deleted key=%s", key)
except Exception as exc: # noqa: BLE001
log.error("event=orphan_delete_failed key=%s type=%s",
key, type(exc).__name__)
# staging/ — удаляем только старое (не in-flight).
for obj in s3.list_objects("staging/"):
lm = obj.get("LastModified")
if lm is None:
continue
if lm.tzinfo is None:
lm = lm.replace(tzinfo=timezone.utc)
if lm > grace_cutoff:
continue
try:
s3.delete_object(obj["Key"])
staging_deleted += 1
except Exception:
pass
# missing
for key in known:
if s3.head_object(key) is None:
missing += 1
log.warning("event=missing_object key=%s", key)
# зависшие processing → queued
try:
recovered = storage.recover_stuck_processing()
if recovered:
log.info("event=stuck_processing_recovered count=%s", recovered)
except Exception as exc: # noqa: BLE001
log.error("event=recover_stuck_failed type=%s", type(exc).__name__)
return {
"scanned": scanned,
"orphan_deleted": orphan_deleted,
"missing": missing,
"known": len(known),
"staging_deleted": staging_deleted,
}
def main() -> None:
init_pool()
interval = _interval()
log.info("event=cleanup_start interval_s=%s grace_s=%s", interval, _grace())
try:
while True:
try:
stats = _run_once()
log.info(
"event=cleanup_pass scanned=%s known=%s orphan_deleted=%s"
" missing=%s staging_deleted=%s",
stats["scanned"], stats["known"], stats["orphan_deleted"],
stats["missing"], stats["staging_deleted"],
)
except Exception as exc: # noqa: BLE001
log.error("event=cleanup_failed type=%s", type(exc).__name__)
time.sleep(interval)
finally:
close_pool()
if __name__ == "__main__":
main()