File size: 4,896 Bytes
b7bf9e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Database configuration and session management.

Provides async engine, session factory, and dependency injection for FastAPI.
"""

import logging
import ssl as ssl_module
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlmodel import SQLModel

from src.api.config import get_settings

logger = logging.getLogger(__name__)

# Lazy initialization - engine created on first use
_engine = None
_async_session_factory = None


def _prepare_async_url(database_url: str) -> tuple[str, dict]:
    """
    Prepare a database URL and connect_args for asyncpg.

    asyncpg does not accept libpq query parameters (sslmode, channel_binding, etc.).
    This function strips all query params from the URL, converts ``sslmode`` into the
    ``ssl`` connect_arg that asyncpg understands, and drops the rest.
    """
    parsed = urlparse(database_url)
    query_params = parse_qs(parsed.query)
    connect_args: dict = {}

    # Convert sslmode to asyncpg's ssl connect_arg
    sslmode = query_params.get("sslmode", [None])[0]
    if sslmode == "verify-full":
        ssl_ctx = ssl_module.create_default_context()
        connect_args["ssl"] = ssl_ctx
    elif sslmode in ("require", "verify-ca", "prefer"):
        connect_args["ssl"] = True

    # Strip ALL query params — they are libpq-specific and unsupported by asyncpg
    parsed = parsed._replace(query="")
    database_url = urlunparse(parsed)

    return database_url, connect_args


def get_engine():
    """
    Get or create the async database engine.

    Pool settings tuned for Neon serverless:
    - pool_size=10: Base connections
    - max_overflow=20: Burst capacity
    - pool_recycle=1800: Reconnect every 30 min
    """
    global _engine
    if _engine is None:
        settings = get_settings()
        url, connect_args = _prepare_async_url(settings.database_url)
        _engine = create_async_engine(
            url,
            echo=False,
            pool_size=10,
            max_overflow=20,
            pool_recycle=1800,
            connect_args=connect_args,
        )
    return _engine


def get_session_factory():
    """Get or create the async session factory."""
    global _async_session_factory
    if _async_session_factory is None:
        _async_session_factory = async_sessionmaker(
            get_engine(),
            class_=AsyncSession,
            expire_on_commit=False,
            autocommit=False,
            autoflush=False,
        )
    return _async_session_factory


async def get_session() -> AsyncGenerator[AsyncSession, None]:
    """
    Dependency that provides an async database session.

    Yields an isolated session for each request.
    Automatically handles cleanup and rollback on exceptions.

    Usage:
        @app.get("/items")
        async def get_items(session: AsyncSession = Depends(get_session)):
            ...
    """
    session_factory = get_session_factory()
    async with session_factory() as session:
        try:
            yield session
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()


async def create_tables() -> None:
    """
    Create all database tables from SQLModel metadata.

    Called during application startup to ensure tables exist.
    """
    engine = get_engine()
    async with engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)
    logger.info("Database tables created successfully")


async def close_engine() -> None:
    """
    Dispose of the database engine and close all connections.

    Called during application shutdown.
    """
    global _engine, _async_session_factory
    if _engine is not None:
        await _engine.dispose()
        _engine = None
        _async_session_factory = None
        logger.info("Database connections closed")


@asynccontextmanager
async def lifespan(app):
    """
    Application lifespan context manager.

    Handles database initialization on startup and cleanup on shutdown.

    Usage:
        app = FastAPI(lifespan=lifespan)
    """
    # Import models to register them with SQLModel.metadata
    from src.api.models import ChatMessage, ChatThread, Task, User  # noqa: F401

    logger.info("Starting database initialization...")
    try:
        await create_tables()
        logger.info("Application startup complete")
    except Exception as e:
        logger.error(f"Failed to initialize database: {e}")
        raise RuntimeError(
            f"Database initialization failed. Check your DATABASE_URL. Error: {e}"
        ) from e

    yield

    logger.info("Shutting down application...")
    await close_engine()
    logger.info("Application shutdown complete")