""" Async SQLAlchemy engine and session factory for PostgreSQL. """ from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import DeclarativeBase from core.config import get_settings settings = get_settings() import sys import os import json from sqlalchemy.pool import NullPool, AsyncAdaptedQueuePool from fastapi.encoders import jsonable_encoder def custom_json_serializer(obj): return json.dumps(jsonable_encoder(obj)) # Definitive Process Identification: # We inspect both environment variables and the actual command line arguments # to ensure we never misidentify a Worker as an API (or vice versa). def is_worker_process() -> bool: if os.environ.get("NEXUS_MODE") == "worker": return True # If arq or nexus_worker is in the command line, we are 100% a background worker for arg in sys.argv: if "arq" in arg.lower() or "nexus_worker" in arg.lower(): return True return False # Global state for lazy engine initialization _engine = None _session_factory = None def get_engine(): """Lazily initialize the SQLAlchemy engine with the correct pooling strategy.""" global _engine if _engine is None: is_worker = is_worker_process() # UNIVERSAL FIX: Every process now uses NullPool (Zero-Footprint). # We rely 100% on the server-side PgBouncer for pooling. pool_class = NullPool if is_worker else AsyncAdaptedQueuePool pool_kwargs = {} if is_worker else { "pool_size": 25, # base resident connections "max_overflow": 45, # burst headroom — total cap = 70 connections "pool_timeout": 10, # fail fast: surface overload quickly vs. hang for 45s "pool_recycle": 300, "pool_pre_ping": True, } _engine = create_async_engine( settings.async_database_url, echo=settings.DEBUG, future=True, poolclass=pool_class, json_serializer=custom_json_serializer, **pool_kwargs, connect_args={ # Use SSL only for cloud/remote databases; local Postgres rarely has SSL enabled "sslmode": "require" if (settings.DATABASE_URL and any( x in settings.DATABASE_URL for x in ("supabase", "neon.tech", "render.com", "railway.app") )) else "prefer", "prepare_threshold": None, # Disable prepared statements for Transaction Mode safety "options": "-c statement_timeout=60000", # Protect pool but allow for AI synthesis } ) return _engine def get_session_factory(): """Lazily initialize the session maker.""" global _session_factory if _session_factory is None: _session_factory = async_sessionmaker( get_engine(), class_=AsyncSession, expire_on_commit=False, ) return _session_factory # Proxy objects for backward compatibility with existing imports class EngineProxy: def __getattr__(self, name): return getattr(get_engine(), name) class SessionFactoryProxy: def __call__(self, **kwargs): return get_session_factory()(**kwargs) def __getattr__(self, name): return getattr(get_session_factory(), name) engine = EngineProxy() async_session_factory = SessionFactoryProxy() class Base(DeclarativeBase): """Base class for all SQLAlchemy models.""" pass async def get_db(): """ Standardize database session management. Yields an async session and ensures proper rollback on exceptions. """ async with async_session_factory() as session: try: yield session # We DON'T auto-commit here anymore as it can cause issues # with partial updates in complex routes. Endpoints should call await db.commit(). except Exception: await session.rollback() raise finally: await session.close() import subprocess from core.logging import get_logger logger = get_logger(__name__) async def run_migrations(): """ Run Alembic migrations automatically on startup with a Distributed Redis Lock. Ensures only one instance executes migrations in multi-pod deployments. """ import asyncio import uuid from core.cache import get_redis_client lock_key = "nexus:infra:migration_lock" # 300s (5m) lock is safer for production migrations lock_ttl = 300 max_retries = 5 retry_delay = 2 redis = get_redis_client() lock_id = str(uuid.uuid4()) try: for attempt in range(max_retries): try: # 1. Acquire Lock with Unique ID acquired = await redis.set(lock_key, lock_id, ex=lock_ttl, nx=True) if acquired: logger.info("🔐 Database Migration Lock ACQUIRED.") try: logger.info("Running Alembic upgrade head...") # Use asyncio.create_subprocess_exec to keep the event loop responsive process = await asyncio.create_subprocess_exec( "alembic", "upgrade", "head", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() if process.returncode == 0: logger.info("✅ Database migrations completed successfully.") else: logger.error(f"❌ Migration failed with exit code {process.returncode}:\n{stderr.decode()}") finally: # 2. RELEASE LOCK: Only if we still own it (Safe Cleanup) current_val = await redis.get(lock_key) if current_val == lock_id: await redis.delete(lock_key) logger.info("🔓 Database Migration Lock RELEASED.") else: logger.warning("⚠️ Could not release lock: Lock was stolen or expired.") return logger.warning(f"⏳ Migration Lock busy, retrying ({attempt+1}/{max_retries})...") await asyncio.sleep(retry_delay) except Exception as e: logger.error(f"❌ Migration Lock Error: {e}") await asyncio.sleep(retry_delay) logger.error("🚫 Failed to acquire Migration Lock after multiple attempts.") except Exception as e: logger.error(f"⚠️ Unexpected error during distributed migration: {e}") # Relinquish the lock if we own it # NOTE: In extremely slow migrations, the lock might auto-expire. # This is safer than a permanent deadlock. try: current_val = await redis.get(lock_key) if current_val == lock_id: await redis.delete(lock_key) logger.info("🔓 Migration Lock released.") except Exception: pass async def init_db(): """DEPRECATED: Use run_migrations instead for proper versioning.""" async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)