import os import sqlite3 from datetime import UTC, datetime, timedelta RETENTION = timedelta(minutes=10) def main(): connection = sqlite3.connect(os.environ["LEDGER_DB"], timeout=5) connection.execute("PRAGMA busy_timeout = 5000") connection.execute("PRAGMA foreign_keys = ON") tables = { row[0] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'table'") } cutoff = (datetime.now(UTC) - RETENTION).isoformat() deleted = [] if "auth_sessions" in tables: cursor = connection.execute( "DELETE FROM auth_sessions WHERE expires_at <= ?", (int(datetime.now(UTC).timestamp()),), ) deleted.append(f"sessions={cursor.rowcount}") if "implant_challenges" in tables: cursor = connection.execute( "DELETE FROM implant_challenges WHERE created_at <= ?", (cutoff,), ) deleted.append(f"challenges={cursor.rowcount}") if "implants" in tables: cursor = connection.execute( "DELETE FROM implants WHERE created_at <= ?", (cutoff,), ) deleted.append(f"implants={cursor.rowcount}") if "users" in tables and "implants" in tables: cursor = connection.execute( "DELETE FROM users WHERE created_at <= ? " "AND NOT EXISTS (SELECT 1 FROM implants WHERE implants.user_id = users.id)", (cutoff,), ) deleted.append(f"users={cursor.rowcount}") connection.commit() connection.execute("PRAGMA wal_checkpoint(PASSIVE)") connection.execute("PRAGMA optimize") connection.execute("PRAGMA incremental_vacuum").fetchall() connection.close() print("cleaned " + " ".join(deleted), flush=True) if __name__ == "__main__": main()