import logging from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from contextlib import asynccontextmanager from typing import AsyncGenerator from app.config import get_settings logger = logging.getLogger(__name__) # ── Primary engine (DATABASE_URL) — backend tables: files, ai_request_logs, ai_cache _engine: AsyncEngine | None = None _session_factory: sessionmaker | None = None # ── RAG engine (DATABASE_RAG_URL) — pgvector tables: rag_chunks, rag_documents, # rag_questions, chat_sessions, chat_messages, rag_queries. # Falls back to the primary engine when DATABASE_RAG_URL is empty. _rag_engine: AsyncEngine | None = None _rag_session_factory: sessionmaker | None = None def _normalise_rag_url(raw: str) -> str: """Ensure DATABASE_RAG_URL uses the asyncpg driver.""" url = raw.strip().strip('"') if url.startswith("postgresql://") or url.startswith("postgres://"): url = url.replace("postgresql://", "postgresql+asyncpg://", 1) url = url.replace("postgres://", "postgresql+asyncpg://", 1) # asyncpg expects `ssl` not `sslmode`, and does not support channel_binding. # Keep TLS behavior by mapping sslmode=require -> ssl=require. if "?" in url: from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit split = urlsplit(url) query_pairs = parse_qsl(split.query, keep_blank_values=True) normalized_pairs: list[tuple[str, str]] = [] ssl_value = None for key, value in query_pairs: k = key.lower() if k == "channel_binding": continue if k == "sslmode": ssl_value = value or "require" continue normalized_pairs.append((key, value)) has_ssl = any(k.lower() == "ssl" for k, _ in normalized_pairs) if ssl_value is not None and not has_ssl: normalized_pairs.append(("ssl", ssl_value)) url = urlunsplit((split.scheme, split.netloc, split.path, urlencode(normalized_pairs), split.fragment)) return url def _normalise_primary_url(raw: str) -> str: """Normalize primary DATABASE_URL for asyncpg compatibility.""" return _normalise_rag_url(raw) async def init_db() -> None: global _engine, _session_factory, _rag_engine, _rag_session_factory settings = get_settings() _engine = create_async_engine( _normalise_primary_url(settings.DATABASE_URL), pool_size=settings.DB_POOL_SIZE, max_overflow=settings.DB_MAX_OVERFLOW, pool_pre_ping=True, pool_recycle=240, # Recycle connections every 4 min (below Neon's 5-min idle timeout) ) _session_factory = sessionmaker( _engine, class_=AsyncSession, expire_on_commit=False, ) # RAG engine — separate DB if configured, otherwise reuse primary rag_url = settings.DATABASE_RAG_URL.strip().strip('"') if rag_url: normalised = _normalise_rag_url(rag_url) _rag_engine = create_async_engine( normalised, pool_size=settings.DB_POOL_SIZE, max_overflow=settings.DB_MAX_OVERFLOW, pool_pre_ping=True, pool_recycle=240, # Recycle connections every 4 min (below Neon's 5-min idle timeout) ) _rag_session_factory = sessionmaker( _rag_engine, class_=AsyncSession, expire_on_commit=False, ) logger.info("RAG database engine initialised (separate DB)") else: _rag_engine = _engine _rag_session_factory = _session_factory logger.info("RAG database engine: using primary DATABASE_URL") async def close_db() -> None: global _engine, _rag_engine if _rag_engine and _rag_engine is not _engine: await _rag_engine.dispose() _rag_engine = None if _engine: await _engine.dispose() _engine = None def get_engine() -> AsyncEngine: if _engine is None: raise RuntimeError("Database not initialised — call init_db() first") return _engine def get_rag_engine() -> AsyncEngine: if _rag_engine is None: raise RuntimeError("Database not initialised — call init_db() first") return _rag_engine async def _safe_close_session(session: AsyncSession) -> None: """Close a session, tolerating already-closed connections (e.g. Neon idle timeout). When the underlying TCP connection is closed by the server while we hold a session (exam generation can take 5+ min), SQLAlchemy's session.close() tries to rollback the connection and raises InterfaceError. Calling session.invalidate() first marks the connection as dead so SQLAlchemy skips the rollback and just discards the connection back to the pool. """ try: await session.close() except Exception: try: await session.invalidate() except Exception: pass @asynccontextmanager async def get_session() -> AsyncGenerator[AsyncSession, None]: if _session_factory is None: raise RuntimeError("Database not initialised — call init_db() first") session: AsyncSession = _session_factory() try: yield session try: await session.commit() except Exception: try: await session.invalidate() except Exception: pass except Exception: try: await session.rollback() except Exception: try: await session.invalidate() except Exception: pass raise finally: await _safe_close_session(session) @asynccontextmanager async def get_rag_session() -> AsyncGenerator[AsyncSession, None]: """Session bound to the RAG database (DATABASE_RAG_URL or fallback). Commit/rollback/close errors on teardown are suppressed — long-running streaming requests (exam generation) hold sessions across Neon's idle connection timeout (~5 min). When the connection is closed by the server, we invalidate it so SQLAlchemy skips the rollback in session.close(). """ if _rag_session_factory is None: raise RuntimeError("Database not initialised — call init_db() first") session: AsyncSession = _rag_session_factory() try: yield session try: await session.commit() except Exception: try: await session.invalidate() except Exception: pass except Exception: try: await session.rollback() except Exception: try: await session.invalidate() except Exception: pass raise finally: await _safe_close_session(session) async def check_db_connection() -> bool: try: async with get_session() as session: await session.execute( __import__("sqlalchemy").text("SELECT 1") ) return True except Exception: return False @asynccontextmanager async def get_async_session() -> AsyncGenerator[AsyncSession, None]: """Backward-compatible alias used by older ingest workers. Prefer get_rag_session() for RAG pipeline operations. """ async with get_rag_session() as session: yield session