""" Create database indexes for refresh token management Run this script once to set up optimal indexes """ import asyncio import sys import os # Add parent directory to path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from app.core.nosql_client import db import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def create_indexes(): """Create indexes for refresh_tokens collection""" try: collection = db["refresh_tokens"] # Unique index on token_id await collection.create_index("token_id", unique=True) logger.info("✓ Created unique index on token_id") # Index on customer_id for user session queries await collection.create_index("customer_id") logger.info("✓ Created index on customer_id") # Index on family_id for token family operations await collection.create_index("family_id") logger.info("✓ Created index on family_id") # Index on expires_at for cleanup operations await collection.create_index("expires_at") logger.info("✓ Created index on expires_at") # Compound index for active session queries await collection.create_index([ ("customer_id", 1), ("revoked", 1), ("expires_at", 1) ]) logger.info("✓ Created compound index on customer_id, revoked, expires_at") # Index on revoked for filtering await collection.create_index("revoked") logger.info("✓ Created index on revoked") # Index on used for rotation checks await collection.create_index("used") logger.info("✓ Created index on used") # TTL index to automatically delete expired tokens after 30 days await collection.create_index( "expires_at", expireAfterSeconds=30 * 24 * 60 * 60 # 30 days ) logger.info("✓ Created TTL index on expires_at (30 days)") logger.info("\n✅ All indexes created successfully!") # List all indexes indexes = await collection.list_indexes().to_list(length=None) logger.info("\nCurrent indexes:") for idx in indexes: logger.info(f" - {idx['name']}: {idx.get('key', {})}") except Exception as e: logger.error(f"❌ Error creating indexes: {str(e)}", exc_info=True) raise async def create_user_indexes(): """Create indexes for customers collection""" try: collection = db["customers"] # Unique index on customer_id await collection.create_index("customer_id", unique=True) logger.info("✓ Created unique index on customer_id") # Unique index on email await collection.create_index("email", unique=True, sparse=True) logger.info("✓ Created unique index on email") # Unique index on phone await collection.create_index("phone", unique=True, sparse=True) logger.info("✓ Created unique index on phone") # Index on auth_mode await collection.create_index("auth_mode") logger.info("✓ Created index on auth_mode") logger.info("\n✅ User indexes created successfully!") except Exception as e: logger.error(f"❌ Error creating user indexes: {str(e)}", exc_info=True) raise async def main(): """Main function to create all indexes""" logger.info("Starting index creation...\n") logger.info("Creating refresh token indexes...") await create_indexes() logger.info("\nCreating user indexes...") await create_user_indexes() logger.info("\n🎉 All database indexes created successfully!") if __name__ == "__main__": asyncio.run(main())