Spaces:
Build error

File size: 7,427 Bytes
7e8cd1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcf6b59
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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