"""Bounded PostgreSQL pool shared by API storage and health checks.""" import os import atexit from functools import lru_cache from pathlib import Path import psycopg from psycopg.rows import dict_row from psycopg_pool import ConnectionPool from psycopg_pool import PoolTimeout def database_url() -> str: path = os.environ.get("DATABASE_URL_FILE") if path: return Path(path).read_text(encoding="utf-8").strip() return os.environ.get("DATABASE_URL", "postgresql:///messenger") @lru_cache(maxsize=1) def pool() -> ConnectionPool: result = ConnectionPool( database_url(), min_size=0, max_size=8, timeout=5, kwargs={"connect_timeout": 5, "options": "-c statement_timeout=5000", "row_factory": dict_row}, open=True, ) atexit.register(result.close) return result def ready() -> bool: try: with pool().connection() as conn: conn.execute("SELECT 1 FROM users LIMIT 0") return True except (psycopg.Error, PoolTimeout, OSError): return False