"""Engine and session factory. Synchronous SQLAlchemy, deliberately. At one camera and a few thousand frames a day the async machinery buys nothing and costs clarity, and the worker's ``FOR UPDATE SKIP LOCKED`` loop is far easier to reason about synchronously. FastAPI runs ``def`` handlers in a threadpool, so this does not block the loop. Revisit only if the MJPEG relay (Phase 6) turns out to want it. """ from __future__ import annotations from collections.abc import Iterator from sqlalchemy import create_engine from sqlalchemy.orm import Session, sessionmaker from .config import get_settings _settings = get_settings() if not _settings.database_url_is_set: # create_engine("") raises "Could not parse SQLAlchemy URL from string ''", # which sends people looking in the wrong place. Say what to actually do. raise RuntimeError( "POORBIRD_DATABASE_URL is not set. Export it, or put it in server/.env:\n" " POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:" "@127.0.0.1:5432/poorbird\n" "See server/deploy/poorbird.env.example. Run 'poorbird check' to verify." ) engine = create_engine( _settings.database_url, pool_size=_settings.db_pool_size, max_overflow=_settings.db_max_overflow, # Past pool_size + max_overflow a caller waits rather than failing. It has # to be finite: without a timeout a pool leak presents as requests hanging # forever instead of as an error naming the pool. pool_timeout=30, pool_pre_ping=True, echo=_settings.db_echo, future=True, ) SessionLocal = sessionmaker(bind=engine, expire_on_commit=False, future=True) def session_scope() -> Iterator[Session]: """Context-managed session for scripts and the worker.""" with SessionLocal() as session: yield session