Files
mtusi2026lab3/app/db.py
T
Artu-RitoandClaude Sonnet 5 2f1cf3afac Лаба 3: Nginx LB, 2 реплики API и общая идемпотентность (оценка 4)
Переиспользован стек lab2 (Postgres/Redis/Argon2id). Добавлены: Nginx
балансировщик перед api1/api2, общая идемпотентность POST-сообщений
(idempotency_keys + advisory-lock сериализация в Postgres), explicit
stop-one/restart hooks. make test/test-persistence/test-failover/validate
зелёные для обеих реплик; найдены и исправлены гонка миграций и гонка
рестарта Nginx/DNS — см. REPORT.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 00:35:53 +03:00

83 lines
2.4 KiB
Python

"""PostgreSQL connection pool and versioned migration runner."""
import logging
from pathlib import Path
import asyncpg
logger = logging.getLogger("app.db")
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
_pool: asyncpg.Pool | None = None
async def init_pool(dsn: str) -> asyncpg.Pool:
global _pool
_pool = await asyncpg.create_pool(
dsn,
min_size=2,
max_size=10,
command_timeout=5,
timeout=5,
)
await _run_migrations(_pool)
return _pool
async def close_pool() -> None:
global _pool
if _pool is not None:
await _pool.close()
_pool = None
def pool() -> asyncpg.Pool:
if _pool is None:
raise RuntimeError("database pool is not initialized")
return _pool
MIGRATION_LOCK_KEY = 783451 # arbitrary advisory-lock id, serializes concurrent replicas
async def _run_migrations(p: asyncpg.Pool) -> None:
async with p.acquire() as conn:
# Multiple API replicas start together; an advisory lock keeps migrations
# from racing each other instead of letting all replicas apply SQL at once.
await conn.execute("SELECT pg_advisory_lock($1)", MIGRATION_LOCK_KEY)
try:
await _apply_migrations(conn)
finally:
await conn.execute("SELECT pg_advisory_unlock($1)", MIGRATION_LOCK_KEY)
async def _apply_migrations(conn: asyncpg.Connection) -> None:
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
applied = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")}
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
if path.name in applied:
continue
sql = path.read_text(encoding="utf-8")
async with conn.transaction():
await conn.execute(sql)
await conn.execute(
"INSERT INTO schema_migrations (version) VALUES ($1)", path.name
)
logger.info("applied migration %s", path.name)
async def ping() -> bool:
try:
async with pool().acquire() as conn:
await conn.fetchval("SELECT 1")
return True
except Exception: # noqa: BLE001 - readiness probe, any failure means not ready
return False