|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +from datetime import datetime, timezone |
| 4 | + |
| 5 | +from sqlalchemy import create_engine, text |
| 6 | +from sqlalchemy.orm import sessionmaker |
| 7 | + |
| 8 | +from config import settings |
| 9 | +from models import OTP, Base |
| 10 | + |
| 11 | +# Set up logging with explicit handler control |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | +# Remove any existing handlers to prevent duplicates |
| 14 | +for handler in logger.handlers[:]: |
| 15 | + logger.removeHandler(handler) |
| 16 | +# Remove root logger handlers |
| 17 | +for handler in logging.getLogger().handlers[:]: |
| 18 | + logging.getLogger().removeHandler(handler) |
| 19 | + |
| 20 | +# Add single stream handler |
| 21 | +handler = logging.StreamHandler() |
| 22 | +handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) |
| 23 | +logger.addHandler(handler) |
| 24 | +logger.setLevel(logging.DEBUG) |
| 25 | + |
| 26 | +# Database setup |
| 27 | +engine = create_engine(settings.database_url) |
| 28 | +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) |
| 29 | + |
| 30 | +def wait_for_db(max_retries=5, retry_interval=5): |
| 31 | + """Wait for database to be available.""" |
| 32 | + retry_count = 0 |
| 33 | + while retry_count < max_retries: |
| 34 | + try: |
| 35 | + db = SessionLocal() |
| 36 | + try: |
| 37 | + db.execute(text("SELECT 1")) |
| 38 | + logger.info("Database connection successful") |
| 39 | + return True |
| 40 | + finally: |
| 41 | + db.close() |
| 42 | + except Exception as e: |
| 43 | + retry_count += 1 |
| 44 | + if retry_count < max_retries: |
| 45 | + logger.warning(f"Database connection attempt {retry_count} failed: {e}") |
| 46 | + logger.info(f"Retrying in {retry_interval} seconds...") |
| 47 | + asyncio.sleep(retry_interval) |
| 48 | + else: |
| 49 | + logger.error(f"Failed to connect to database after {max_retries} attempts: {e}") |
| 50 | + return False |
| 51 | + return False |
| 52 | + |
| 53 | +def cleanup_expired_otps(): |
| 54 | + """Delete expired OTPs from the database.""" |
| 55 | + try: |
| 56 | + db = SessionLocal() |
| 57 | + try: |
| 58 | + # Use timezone-aware UTC for comparison to match models |
| 59 | + now = datetime.now(timezone.utc) |
| 60 | + logger.debug(f"Running cleanup check at {now}") |
| 61 | + |
| 62 | + result = db.query(OTP).filter( |
| 63 | + OTP.expires_at < now |
| 64 | + ).delete() |
| 65 | + db.commit() |
| 66 | + |
| 67 | + # Always log the check, even if no deletions |
| 68 | + if result > 0: |
| 69 | + logger.info(f"Deleted {result} expired OTPs") |
| 70 | + else: |
| 71 | + logger.debug("No expired OTPs found to delete") |
| 72 | + |
| 73 | + finally: |
| 74 | + db.close() |
| 75 | + except Exception as e: |
| 76 | + logger.error(f"Error cleaning up expired OTPs: {e}") |
| 77 | + |
| 78 | +async def run_cleanup_loop(): |
| 79 | + """Run the cleanup task periodically.""" |
| 80 | + logger.info(f"Starting cleanup loop with interval: {settings.CLEANUP_INTERVAL_SECONDS} seconds") |
| 81 | + |
| 82 | + while True: |
| 83 | + logger.debug("Running cleanup cycle...") |
| 84 | + cleanup_expired_otps() |
| 85 | + logger.debug(f"Sleeping for {settings.CLEANUP_INTERVAL_SECONDS} seconds...") |
| 86 | + await asyncio.sleep(settings.CLEANUP_INTERVAL_SECONDS) |
| 87 | + |
| 88 | +def main(): |
| 89 | + # Only show startup banner once |
| 90 | + logger.info("Starting OTP cleanup service...") |
| 91 | + logger.info(f"Database URL: {settings.database_url.replace(settings.POSTGRES_PASSWORD, '****')}") |
| 92 | + logger.info(f"Cleanup interval: {settings.CLEANUP_INTERVAL_SECONDS} seconds") |
| 93 | + |
| 94 | + # Wait for database with retries |
| 95 | + if not wait_for_db(): |
| 96 | + logger.error("Failed to connect to database after retries. Exiting.") |
| 97 | + return |
| 98 | + |
| 99 | + try: |
| 100 | + # Run the cleanup loop |
| 101 | + asyncio.run(run_cleanup_loop()) |
| 102 | + except KeyboardInterrupt: |
| 103 | + logger.info("Shutting down OTP cleanup service...") |
| 104 | + except Exception as e: |
| 105 | + logger.error(f"Error in cleanup service: {e}") |
| 106 | + raise |
| 107 | + |
| 108 | +if __name__ == "__main__": |
| 109 | + main() |
0 commit comments