Spaces:
Running on T4
Running on T4
File size: 3,123 Bytes
be69d1e 2756f0f be69d1e 7a3215f 2756f0f be69d1e 2756f0f be69d1e 2756f0f 7a3215f be69d1e 7a3215f be69d1e 2756f0f be69d1e 2756f0f | 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 | """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
|