Files
mtusi2026lab7/scripts/cleanup_staging.py
T

49 lines
1.8 KiB
Python

#!/usr/bin/env python3
"""Remove old staging objects only when no live attachment needs them."""
import os
import sys
from datetime import datetime, timezone
import psycopg
from jobs import s3_client
DB = os.environ["DATABASE_URL"]
BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
RETENTION = max(3600, int(os.getenv("STAGING_RETENTION_SECONDS", "86400")))
def main():
dry_run = "--apply" not in sys.argv
s3 = s3_client()
removed = kept = 0
token = None
while True:
args = {"Bucket": BUCKET, "Prefix": "staging/", "MaxKeys": 500}
if token: args["ContinuationToken"] = token
page = s3.list_objects_v2(**args)
for obj in page.get("Contents", []):
key, modified = obj["Key"], obj["LastModified"]
age = (datetime.now(timezone.utc) - modified).total_seconds()
if age < RETENTION:
kept += 1; continue
with psycopg.connect(DB) as conn:
# Replay takes the same row lock before validating the retained input.
live = conn.execute(
"SELECT status,updated_at FROM attachments WHERE staging_key=%s FOR UPDATE", (key,)
).fetchone()
if live and (live[0] in ("queued", "processing") or
(datetime.now(timezone.utc) - live[1]).total_seconds() < RETENTION):
kept += 1
continue
if not dry_run:
s3.delete_object(Bucket=BUCKET, Key=key)
removed += 1
if not page.get("IsTruncated"):
break
token = page["NextContinuationToken"]
print(f"mode={'dry-run' if dry_run else 'apply'} retention_seconds={RETENTION} candidates={removed} kept={kept}")
if __name__ == "__main__":
main()