feat: перевести API на password/Basic/Bearer и PostgreSQL с Redis-кэшем

Co-authored-by: aider (deepseek/deepseek-chat) <aider@aider.chat>
This commit is contained in:
Evgeny Bushkov
2026-10-23 18:07:09 +03:00
co-authored by aider
parent 3e152d4175
commit 785fde833f
18 changed files with 856 additions and 176 deletions
+53
View File
@@ -0,0 +1,53 @@
"""Пул соединений PostgreSQL и применение миграций."""
import logging
import os
from pathlib import Path
import psycopg
from psycopg_pool import ConnectionPool
logger = logging.getLogger("messenger.db")
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
def make_pool() -> ConnectionPool:
dsn = os.environ.get("DATABASE_URL")
if not dsn:
raise RuntimeError("DATABASE_URL is not set")
pool = ConnectionPool(
conninfo=dsn,
min_size=int(os.environ.get("DB_POOL_MIN", "1")),
max_size=int(os.environ.get("DB_POOL_MAX", "10")),
timeout=float(os.environ.get("DB_CONNECT_TIMEOUT", "3")),
kwargs={"autocommit": False},
open=False,
)
pool.open(wait=True, timeout=float(os.environ.get("DB_CONNECT_TIMEOUT", "3")))
return pool
def apply_migrations(pool: ConnectionPool) -> None:
"""Идемпотентно применяет *.sql из migrations/ в лексикографическом порядке."""
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations ("
" version TEXT PRIMARY KEY,"
" applied_at TIMESTAMPTZ NOT NULL DEFAULT now())"
)
conn.commit()
cur.execute("SELECT version FROM schema_migrations")
applied = {row[0] for row in cur.fetchall()}
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
version = path.stem
if version in applied:
continue
logger.info("applying migration %s", version)
sql = path.read_text(encoding="utf-8")
with conn.transaction():
with conn.cursor() as cur:
cur.execute(sql)
cur.execute(
"INSERT INTO schema_migrations(version) VALUES (%s)", (version,)
)