import argparse import asyncio import os from datetime import datetime, timedelta, timezone from sqlalchemy import text from src.database import SessionFactory, engine from src.storage import delete_object, object_exists RETENTION_SECONDS = int(os.getenv("STAGING_RETENTION_SECONDS", "86400")) async def cleanup(apply: bool): cutoff = datetime.now(timezone.utc) - timedelta(seconds=RETENTION_SECONDS) async with SessionFactory() as session: result = await session.execute( text(""" SELECT a.id, a.chat_id, a.content_type, a.s3_key, a.created_at FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id WHERE a.status = 'ready' AND j.status = 'ready' AND a.s3_key LIKE 'attachments/%' AND a.created_at < :cutoff """), {"cutoff": cutoff}, ) rows = result.all() candidates = 0 for row in rows: extension = "png" if row.content_type == "image/png" else "jpg" staging_key = f"staging/{row.chat_id}/{row.id}.{extension}" if not await object_exists(staging_key): continue candidates += 1 if not apply: print(f"DRY RUN: {staging_key}") continue await delete_object(staging_key) print(f"DELETED: {staging_key}") print(f"Candidates: {candidates}") async def main(): parser = argparse.ArgumentParser() parser.add_argument("--apply", action="store_true") args = parser.parse_args() try: await cleanup(args.apply) finally: await engine.dispose() if __name__ == "__main__": asyncio.run(main())