Files
mtusi2026lab3/app/db.py
T

159 lines
5.0 KiB
Python

"""PostgreSQL access: bounded pool, timeouts, and versioned migrations.
The API does not race migrations on every replica. Compose runs the one-shot
``migrate`` service first; API processes only verify that the expected schema is
present. ``python -m app.migrate`` is also the local/manual entry point.
"""
from __future__ import annotations
import logging
import threading
import time
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .config import settings
log = logging.getLogger("messenger.db")
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
LOCK_ID = 0x4D545553 # stable application-wide advisory lock
_pool: ConnectionPool | None = None
_pool_lock = threading.Lock()
_migrated = threading.Event()
_started = False
_start_lock = threading.Lock()
def _create_pool() -> ConnectionPool:
options = (
f"-c statement_timeout={settings.db_statement_timeout_ms} "
"-c idle_in_transaction_session_timeout=10000 "
"-c lock_timeout=3000"
)
return ConnectionPool(
conninfo=settings.database_url,
min_size=settings.db_pool_min,
max_size=settings.db_pool_max,
timeout=settings.db_pool_acquire_timeout,
open=False,
kwargs={
"row_factory": dict_row,
"connect_timeout": settings.db_connect_timeout,
"application_name": "mtusi-messenger-lab3",
"options": options,
},
)
def pool() -> ConnectionPool:
global _pool
with _pool_lock:
if _pool is None:
_pool = _create_pool()
return _pool
def _migration_files() -> list[Path]:
return sorted(MIGRATIONS_DIR.glob("*.sql"))
def apply_migrations() -> None:
"""Apply every migration exactly once.
A session-level advisory lock serialises concurrent migration runners.
Each migration and its schema_migrations row share one transaction.
"""
with pool().connection() as conn:
conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,))
try:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
)
"""
)
applied = {
row["version"]
for row in conn.execute("SELECT version FROM schema_migrations").fetchall()
}
for path in _migration_files():
version = path.stem
if version in applied:
continue
log.info("applying migration %s", version)
conn.execute(path.read_text(encoding="utf-8"))
conn.execute(
"INSERT INTO schema_migrations(version) VALUES (%s)", (version,)
)
finally:
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
def schema_is_current() -> bool:
"""True when every migration shipped in this image is already applied."""
expected = {path.stem for path in _migration_files()}
if not expected:
return False
try:
with pool().connection(timeout=1.0) as conn:
row = conn.execute(
"SELECT to_regclass('public.schema_migrations') IS NOT NULL AS present"
).fetchone()
if not row or not row["present"]:
return False
applied = {
item["version"]
for item in conn.execute("SELECT version FROM schema_migrations").fetchall()
}
return expected.issubset(applied)
except Exception:
return False
def start_background_initialisation() -> None:
"""Open the pool and verify schema without making /health/live depend on DB."""
global _started
with _start_lock:
if _started:
return
_started = True
def run() -> None:
backoff = 0.5
opened = False
while True:
try:
if not opened:
pool().open(wait=True, timeout=5)
opened = True
if not schema_is_current():
log.warning("database schema is not current; waiting for migrate service")
raise RuntimeError("schema is not current")
_migrated.set()
log.info("database pool is ready and schema is current")
return
except Exception as exc: # startup is retried; request path stays bounded
log.warning("database initialisation is not ready: %s", type(exc).__name__)
time.sleep(backoff)
backoff = min(backoff * 2, 5.0)
threading.Thread(target=run, name="db-init", daemon=True).start()
def is_migrated() -> bool:
return _migrated.is_set()
def close_pool() -> None:
global _pool
with _pool_lock:
if _pool is not None:
_pool.close()
_pool = None