contiai / apps /api /app /db /session.py
aliroya's picture
ContiAI platform: API and queue worker in one container
57fa15f verified
Raw History Blame Contribute Delete
3.16 kB
"""Async engine and session factory."""
from collections.abc import AsyncGenerator
from fastapi import APIRouter, Request, Response
from fastapi.routing import APIRoute
from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.core.config import settings
engine = create_async_engine(
settings.database_url,
echo=settings.debug and settings.env == "local",
pool_pre_ping=True,
pool_size=10,
max_overflow=20,
)
if engine.dialect.name == "sqlite":
# SQLite ignores foreign keys unless asked, per connection. Every
# ON DELETE CASCADE in the schema was therefore decorative here: deleting
# an account left its projects behind pointing at nobody, and Postgres and
# local development disagreed about what the same schema meant.
@event.listens_for(engine.sync_engine, "connect")
def _enforce_foreign_keys(dbapi_connection, _record): # noqa: ANN001
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
SessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# Where the request's session is parked so the route wrapper below can reach
# it. Set by get_session, read once per request; nothing else touches it.
_STATE_KEY = "db_session"
async def get_session(request: Request) -> AsyncGenerator[AsyncSession, None]:
"""FastAPI dependency. Rolls back on any exception.
It deliberately does **not** commit here. A dependency with ``yield``
finalises *after* the response has been sent, so committing at this point
means a client can receive 200 and fire its next request before the write
has landed - which showed up as an account that was approved, said so in
the response, and still read as pending one request later.
The commit happens in :class:`CommittingRoute` instead, which runs before
the response leaves. This block keeps the rollback, because unwinding a
failed request after the fact is exactly the right time for that.
"""
async with SessionLocal() as session:
setattr(request.state, _STATE_KEY, session)
try:
yield session
except Exception:
await session.rollback()
raise
class CommittingRoute(APIRoute):
"""Commits the request's session before the response is returned.
Putting it here rather than in each handler means a new endpoint cannot
forget to commit, and a reviewer never has to check whether it did.
"""
def get_route_handler(self):
original = super().get_route_handler()
async def handler(request: Request) -> Response:
response = await original(request)
session: AsyncSession | None = getattr(request.state, _STATE_KEY, None)
if session is not None and session.in_transaction():
await session.commit()
return response
return handler
def committing_router(**kwargs) -> APIRouter:
"""An APIRouter whose routes commit before responding."""
return APIRouter(route_class=CommittingRoute, **kwargs)