"""Async engine, session factory and the per-request unit of work. The database is a network hop away, so each round trip costs far more than the query itself. Requests therefore avoid the round trips that carry no query: the per-checkout ping, and BEGIN/COMMIT around reads. """ import time import uuid from collections.abc import AsyncIterator from functools import lru_cache from fastapi import Request from sqlalchemy import event from sqlalchemy.exc import DisconnectionError from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine from app.core.config import get_settings # A connection used this recently is assumed alive; one idle for longer is pinged before reuse. IDLE_PING_AFTER_S = 30.0 @lru_cache def get_engine() -> AsyncEngine: settings = get_settings() connect_args = {} if settings.database_transaction_pooler: connect_args = {"statement_cache_size": 0, "prepared_statement_name_func": lambda: f"__asyncpg_{uuid.uuid4().hex}__"} engine = create_async_engine( settings.database_url, pool_size=settings.database_pool_size, max_overflow=settings.database_max_overflow, pool_timeout=settings.database_pool_timeout_s, connect_args=connect_args) # pool_pre_ping costs three round trips (BEGIN, ping, ROLLBACK) on every checkout, so ping idle connections only. @event.listens_for(engine.sync_engine, "checkin") def mark_idle(dbapi_connection, record): record.info["idle_since"] = time.monotonic() @event.listens_for(engine.sync_engine, "checkout") def ping_if_idle(dbapi_connection, record, proxy): if time.monotonic() - record.info.get("idle_since", float("inf")) > IDLE_PING_AFTER_S: try: dbapi_connection.ping() except Exception as exc: raise DisconnectionError() from exc # the pool discards it and checks out a fresh connection return engine @lru_cache def get_autocommit_engine() -> AsyncEngine: """The same pool without BEGIN/COMMIT: for reads and single-statement writes.""" return get_engine().execution_options(isolation_level="AUTOCOMMIT") @lru_cache def get_session_factory() -> async_sessionmaker[AsyncSession]: return async_sessionmaker(get_engine(), expire_on_commit=False) async def get_db(request: Request) -> AsyncIterator[AsyncSession]: """One transaction per request: commit when the handler succeeds, roll back on any error. GET and HEAD run in autocommit. They only read, and under READ COMMITTED each statement sees its own snapshot with or without a transaction, so this saves two round trips and changes no result. A GET handler that writes more than one statement must not rely on this session for atomicity. """ read_only = request.method in ("GET", "HEAD") async with get_session_factory()(**({"bind": get_autocommit_engine()} if read_only else {})) as session: try: yield session await session.commit() except BaseException: await session.rollback() raise