forked from mtusi2026/mtusi2026lab7
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия: - внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial; - TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL), Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA; - OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь; - роли БД, S3-политики и права брокера по принципу минимальных прав; - Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS; - hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия; - отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
156 lines
6.9 KiB
Python
156 lines
6.9 KiB
Python
"""DB <-> S3 reconciliation and staging retention (lab4 reconciler extended for the lab5 key layout).
|
|
|
|
Key layout (all keys are generated by the server):
|
|
staging/<attachment_id> written by the API before 202, read by the worker
|
|
attachments/<attachment_id>/original server-side copy made by the worker
|
|
attachments/<attachment_id>/v<N>/<variant>.* variants of pipeline version N
|
|
Invariant: a row is inserted as 'uploading' BEFORE the staging object is written, so every object has a row.
|
|
|
|
Cases (all gated by a grace period so in-flight work is never touched):
|
|
stale_uploading row 'uploading' older than grace AND its staging object (if any) older than grace -> delete both
|
|
orphan_object object without any row/variant row, older than grace -> delete object
|
|
staging_done staging object of a 'ready' attachment (worker crashed before its own cleanup) -> delete
|
|
staging_expired staging object of a 'failed' attachment older than STAGING_RETENTION_SECONDS -> delete
|
|
(after that a replay is refused; the attachment stays failed and visible)
|
|
missing_object 'ready' row whose original is gone (re-checked by HEAD) -> 'failed'/object_missing
|
|
Queued/processing work is never touched: its staging object is the input of a live job.
|
|
"""
|
|
import logging
|
|
import time
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from app import config
|
|
|
|
log = logging.getLogger("messenger.reconcile")
|
|
|
|
LOCK_ID = 2026_0104
|
|
PREFIXES = ("staging/", "attachments/")
|
|
BATCH = 500
|
|
|
|
|
|
async def run(db, s3, grace_seconds: int, dry_run: bool = True) -> dict:
|
|
started = time.monotonic()
|
|
result = {
|
|
"dry_run": dry_run, "grace_seconds": grace_seconds,
|
|
"stale_uploading": 0, "orphan_objects": 0, "missing_objects": 0, "staging_done": 0, "staging_expired": 0,
|
|
"deleted_objects": 0, "removed_rows": 0, "marked_failed": 0,
|
|
"objects_scanned": 0, "rows_scanned": 0, "protected_fresh_objects": 0,
|
|
}
|
|
async with db.connection() as conn:
|
|
cur = await conn.execute("SELECT pg_try_advisory_lock(%s) AS got", (LOCK_ID,))
|
|
if not (await cur.fetchone())["got"]:
|
|
return {"skipped": "another reconciler is running"}
|
|
try:
|
|
now = datetime.now(timezone.utc)
|
|
cutoff = now - timedelta(seconds=grace_seconds)
|
|
await _stale_uploading(conn, s3, cutoff, dry_run, result)
|
|
await _staging_cleanup(conn, s3, now - timedelta(seconds=config.STAGING_RETENTION_SECONDS), dry_run, result)
|
|
await _orphan_objects(conn, s3, cutoff, dry_run, result)
|
|
await _missing_objects(conn, s3, cutoff, dry_run, result)
|
|
finally:
|
|
await conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
|
|
result["seconds"] = round(time.monotonic() - started, 3)
|
|
return result
|
|
|
|
|
|
async def _stale_uploading(conn, s3, cutoff, dry_run, result):
|
|
cur = await conn.execute(
|
|
"SELECT id, coalesce(staging_key, object_key) AS key FROM attachments"
|
|
" WHERE status = 'uploading' AND created_at < %s",
|
|
(cutoff,),
|
|
)
|
|
for row in await cur.fetchall():
|
|
modified = await run_in_threadpool(s3.head, row["key"])
|
|
if modified is not None and modified >= cutoff:
|
|
result["protected_fresh_objects"] += 1
|
|
continue
|
|
result["stale_uploading"] += 1
|
|
if dry_run:
|
|
continue
|
|
if modified is not None:
|
|
await run_in_threadpool(s3.delete, row["key"])
|
|
result["deleted_objects"] += 1
|
|
done = await conn.execute(
|
|
"DELETE FROM attachments WHERE id = %s AND status = 'uploading' AND created_at < %s", (row["id"], cutoff),
|
|
)
|
|
result["removed_rows"] += done.rowcount
|
|
|
|
|
|
async def _staging_cleanup(conn, s3, retention_cutoff, dry_run, result):
|
|
cur = await conn.execute(
|
|
"SELECT id, staging_key, status FROM attachments WHERE staging_key IS NOT NULL"
|
|
" AND (status = 'ready' OR (status = 'failed' AND updated_at < %s))",
|
|
(retention_cutoff,),
|
|
)
|
|
for row in await cur.fetchall():
|
|
if await run_in_threadpool(s3.head, row["staging_key"]) is None:
|
|
continue
|
|
result["staging_done" if row["status"] == "ready" else "staging_expired"] += 1
|
|
if dry_run:
|
|
continue
|
|
again = await conn.execute(
|
|
"SELECT status FROM attachments WHERE id = %s AND (status = 'ready' OR (status = 'failed' AND updated_at < %s))",
|
|
(row["id"], retention_cutoff),
|
|
)
|
|
if await again.fetchone() is not None:
|
|
await run_in_threadpool(s3.delete, row["staging_key"])
|
|
result["deleted_objects"] += 1
|
|
|
|
|
|
async def _known_keys(conn, keys):
|
|
cur = await conn.execute(
|
|
"SELECT object_key AS k FROM attachments WHERE object_key = ANY(%s)"
|
|
" UNION SELECT staging_key FROM attachments WHERE staging_key = ANY(%s)"
|
|
" UNION SELECT object_key FROM attachment_variants WHERE object_key = ANY(%s)",
|
|
(keys, keys, keys),
|
|
)
|
|
return {row["k"] for row in await cur.fetchall()}
|
|
|
|
|
|
async def _orphan_objects(conn, s3, cutoff, dry_run, result):
|
|
for prefix in PREFIXES:
|
|
pages = await run_in_threadpool(lambda: iter(s3.list_pages(prefix)))
|
|
while True:
|
|
page = await run_in_threadpool(next, pages, None)
|
|
if page is None:
|
|
break
|
|
result["objects_scanned"] += len(page)
|
|
keys = [o["Key"] for o in page]
|
|
if not keys:
|
|
continue
|
|
known = await _known_keys(conn, keys)
|
|
for obj in page:
|
|
if obj["Key"] in known or obj["LastModified"] >= cutoff:
|
|
continue
|
|
result["orphan_objects"] += 1
|
|
if not dry_run and not await _known_keys(conn, [obj["Key"]]):
|
|
await run_in_threadpool(s3.delete, obj["Key"])
|
|
result["deleted_objects"] += 1
|
|
|
|
|
|
async def _missing_objects(conn, s3, cutoff, dry_run, result):
|
|
last = None
|
|
while True:
|
|
cur = await conn.execute(
|
|
"SELECT id, object_key FROM attachments WHERE status = 'ready' AND updated_at < %s"
|
|
" AND (%s::uuid IS NULL OR id > %s::uuid) ORDER BY id LIMIT %s",
|
|
(cutoff, last, last, BATCH),
|
|
)
|
|
rows = await cur.fetchall()
|
|
if not rows:
|
|
return
|
|
for row in rows:
|
|
result["rows_scanned"] += 1
|
|
if await run_in_threadpool(s3.exists, row["object_key"]):
|
|
continue
|
|
result["missing_objects"] += 1
|
|
if not dry_run:
|
|
done = await conn.execute(
|
|
"UPDATE attachments SET status = 'failed', error_code = 'object_missing',"
|
|
" updated_at = clock_timestamp() WHERE id = %s AND status = 'ready'", (row["id"],),
|
|
)
|
|
result["marked_failed"] += done.rowcount
|
|
last = str(rows[-1]["id"])
|