forked from mtusi2026/mtusi2026lab4
208 lines
8.1 KiB
Python
208 lines
8.1 KiB
Python
"""Conservative, repeatable PG/S3 reconciliation. Dry-run is the default."""
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
from collections import Counter
|
|
from datetime import timedelta
|
|
from time import perf_counter
|
|
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
|
|
from messenger.settings import Settings
|
|
from messenger.storage import ObjectStore
|
|
|
|
OWNED = re.compile(r"originals/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\Z")
|
|
|
|
|
|
class Reconciler:
|
|
def __init__(self, conn, store, *, apply=False, grace=300):
|
|
if grace < 300:
|
|
raise ValueError("Minimum grace period is 300 seconds")
|
|
self.conn, self.store, self.apply, self.grace = conn, store, apply, grace
|
|
self.counts, self.actions = Counter(), []
|
|
|
|
def action(self, kind, id):
|
|
self.counts[kind] += 1
|
|
if len(self.actions) < 100:
|
|
self.actions.append({"action": kind, "id": str(id)})
|
|
|
|
def head(self, key):
|
|
self.counts["s3_head"] += 1
|
|
return self.store.head(key)
|
|
|
|
def objects(self, cutoff):
|
|
paginator = self.store.client.get_paginator("list_objects_v2")
|
|
for page in paginator.paginate(
|
|
Bucket=self.store.bucket, Prefix="originals/", PaginationConfig={"PageSize": 1000}
|
|
):
|
|
self.counts["s3_list_pages"] += 1
|
|
for item in page.get("Contents", []):
|
|
self.counts["s3_objects"] += 1
|
|
key = item["Key"]
|
|
if not OWNED.fullmatch(key):
|
|
self.counts["foreign_keys_ignored"] += 1
|
|
continue
|
|
if item["LastModified"] >= cutoff:
|
|
self.counts["fresh_objects_skipped"] += 1
|
|
continue
|
|
with self.conn.transaction():
|
|
existing = self.conn.execute(
|
|
"SELECT id FROM attachments WHERE object_key=%s FOR UPDATE",
|
|
(key,),
|
|
).fetchone()
|
|
if existing:
|
|
continue
|
|
# Re-check immutable generation/age immediately before deleting an orphan.
|
|
current = self.head(key)
|
|
if (
|
|
current is None
|
|
or current["LastModified"] >= cutoff
|
|
or current["ETag"] != item["ETag"]
|
|
or current["ContentLength"] != item["Size"]
|
|
):
|
|
continue
|
|
self.action("delete_orphan", key.removeprefix("originals/"))
|
|
if self.apply:
|
|
self.store.client.delete_object(Bucket=self.store.bucket, Key=key)
|
|
self.counts["s3_delete"] += 1
|
|
|
|
@staticmethod
|
|
def matches(row, head):
|
|
return (
|
|
head is not None
|
|
and head["ContentLength"] == row["size_bytes"]
|
|
and head.get("ContentType") == row["content_type"]
|
|
and head.get("Metadata", {}).get("sha256") == row["sha256"]
|
|
)
|
|
|
|
def metadata(self, cutoff):
|
|
last = "00000000-0000-0000-0000-000000000000"
|
|
while True:
|
|
batch = self.conn.execute(
|
|
"SELECT id FROM attachments WHERE id>%s::uuid ORDER BY id LIMIT 100",
|
|
(last,),
|
|
).fetchall()
|
|
self.counts["pg_metadata_pages"] += 1
|
|
if not batch:
|
|
break
|
|
for value in batch:
|
|
id = value["id"]
|
|
last = str(id)
|
|
self.counts["pg_attachments"] += 1
|
|
with self.conn.transaction():
|
|
row = self.conn.execute(
|
|
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (id,)
|
|
).fetchone()
|
|
if row is None:
|
|
continue
|
|
state = row["storage_state"]
|
|
if row["updated_at"] >= cutoff and state != "missing":
|
|
self.counts["fresh_metadata_skipped"] += 1
|
|
continue
|
|
head = self.head(row["object_key"])
|
|
valid = self.matches(row, head)
|
|
if state == "pending" and head is None:
|
|
used = self.conn.execute(
|
|
"SELECT 1 FROM message_attachments WHERE attachment_id=%s LIMIT 1",
|
|
(id,),
|
|
).fetchone()
|
|
if used:
|
|
self.action("review_used_pending", id)
|
|
continue
|
|
self.action("delete_abandoned_intent", id)
|
|
if self.apply:
|
|
self.conn.execute("DELETE FROM attachments WHERE id=%s", (id,))
|
|
elif state in ("pending", "missing") and valid:
|
|
self.action("restore_ready", id)
|
|
if self.apply:
|
|
self.conn.execute(
|
|
"UPDATE attachments SET storage_state='ready',"
|
|
"updated_at=clock_timestamp() WHERE id=%s",
|
|
(id,),
|
|
)
|
|
elif state == "ready" and not valid:
|
|
self.action("mark_missing", id)
|
|
if self.apply:
|
|
self.conn.execute(
|
|
"UPDATE attachments SET storage_state='missing',"
|
|
"updated_at=clock_timestamp() WHERE id=%s",
|
|
(id,),
|
|
)
|
|
elif state == "pending" and not valid:
|
|
self.action("review_invalid_pending", id)
|
|
elif state == "missing":
|
|
self.counts["still_missing"] += 1
|
|
else:
|
|
self.counts["ready_preserved"] += 1
|
|
|
|
def run(self):
|
|
started = perf_counter()
|
|
if not self.conn.execute("SELECT pg_try_advisory_lock(2301004) AS locked").fetchone()[
|
|
"locked"
|
|
]:
|
|
raise RuntimeError("Another reconciler is active")
|
|
try:
|
|
cutoff = self.conn.execute("SELECT clock_timestamp() AS now").fetchone()["now"]
|
|
cutoff -= timedelta(seconds=self.grace)
|
|
self.store.ready() # Permission/network errors are never interpreted as missing bytes.
|
|
self.objects(cutoff)
|
|
self.metadata(cutoff)
|
|
return {
|
|
"mode": "apply" if self.apply else "dry-run",
|
|
"grace_seconds": self.grace,
|
|
"elapsed_seconds": perf_counter() - started,
|
|
"counts": dict(self.counts),
|
|
"actions": self.actions,
|
|
"actions_preview_limit": 100,
|
|
}
|
|
finally:
|
|
self.conn.execute("SELECT pg_advisory_unlock(2301004)")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--apply", action="store_true")
|
|
parser.add_argument("--grace-seconds", type=int, default=300)
|
|
args = parser.parse_args()
|
|
if args.grace_seconds < 300:
|
|
parser.error("Grace period must be at least 300 seconds")
|
|
store = None
|
|
try:
|
|
settings = Settings.from_env()
|
|
store = ObjectStore(settings)
|
|
with psycopg.connect(
|
|
settings.database_url,
|
|
autocommit=True,
|
|
row_factory=dict_row,
|
|
connect_timeout=2,
|
|
options="-c lock_timeout=1000 "
|
|
"-c statement_timeout=2500 -c idle_in_transaction_session_timeout=5000 "
|
|
"-c timezone=UTC",
|
|
) as conn:
|
|
print(
|
|
json.dumps(
|
|
Reconciler(conn, store, apply=args.apply, grace=args.grace_seconds).run(),
|
|
ensure_ascii=False,
|
|
)
|
|
)
|
|
except Exception as exc:
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"error": "reconciliation_incomplete",
|
|
"type": type(exc).__name__,
|
|
"changes_may_have_committed": args.apply,
|
|
}
|
|
)
|
|
)
|
|
raise SystemExit(1) from None
|
|
finally:
|
|
if store:
|
|
store.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|