feat: добавить каркас приложения с PostgreSQL, сессиями и Redis-кэшем

This commit is contained in:
Evgeny Bushkov
2026-11-06 00:22:27 +03:00
committed by Evgeny Bushkov (aider)
parent 0ab3a341aa
commit d8ba046033
6 changed files with 237 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""MTUSI Messenger — лабораторная 2: PostgreSQL, сессии и Redis-кэш."""
+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,)
)
+16
View File
@@ -0,0 +1,16 @@
"""Единый формат ошибок API и исключение ApiError."""
from typing import Any
class ApiError(Exception):
"""Ошибка, которую нужно вернуть клиенту в формате контракта."""
def __init__(self, status: int, code: str, message: str) -> None:
super().__init__(message)
self.status = status
self.code = code
self.message = message
def error_body(code: str, message: str, request_id: str) -> dict[str, Any]:
return {"error": {"code": code, "message": message, "request_id": request_id}}
+122
View File
@@ -0,0 +1,122 @@
"""Точка входа: FastAPI-приложение, middleware и обработка ошибок."""
import logging
import os
import uuid
import redis
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from .db import apply_migrations, make_pool
from .errors import ApiError, error_body
from .handlers import router
from .sessions import SessionStore
from .store import Store
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger = logging.getLogger("messenger")
app = FastAPI(title="MTUSI Messenger", version="1.2.0")
_pool = make_pool()
apply_migrations(_pool)
_cache: redis.Redis | None = None
_cache_url = os.environ.get("CACHE_URL")
if _cache_url:
_cache = redis.Redis.from_url(
_cache_url,
socket_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT", "1")),
socket_connect_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT", "1")),
decode_responses=False,
)
app.state.pool = _pool
app.state.store = Store(_pool)
app.state.sessions = SessionStore(_pool, _cache)
app.include_router(router)
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
request.state.request_id = request_id
try:
response = await call_next(request)
except ApiError as exc:
response = JSONResponse(
error_body(exc.code, exc.message, request_id),
status_code=exc.status,
)
response.headers["X-Request-Id"] = request_id
return response
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
headers = {"X-Request-Id": request_id}
challenge = getattr(exc, "challenge", None)
if challenge:
headers["WWW-Authenticate"] = challenge
return JSONResponse(
error_body(exc.code, exc.message, request_id),
status_code=exc.status,
headers=headers,
)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
return JSONResponse(
error_body("invalid_request", "Некорректный запрос", request_id),
status_code=400,
headers={"X-Request-Id": request_id},
)
@app.exception_handler(StarletteHTTPException)
async def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
"""Ошибки разбора тела (невалидный JSON/байты) FastAPI отдаёт как HTTPException 400."""
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
if exc.status_code == 400:
return JSONResponse(
error_body("invalid_request", "Некорректный запрос", request_id),
status_code=400,
headers={"X-Request-Id": request_id},
)
return JSONResponse(
error_body("not_found" if exc.status_code == 404 else "internal_error",
str(exc.detail), request_id),
status_code=exc.status_code,
headers={"X-Request-Id": request_id},
)
@app.exception_handler(Exception)
async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse:
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
logger.exception("unhandled error request_id=%s", request_id)
return JSONResponse(
error_body("internal_error", "Внутренняя ошибка", request_id),
status_code=500,
headers={"X-Request-Id": request_id},
)
def main() -> None:
import uvicorn
host = os.environ.get("APP_HOST", "0.0.0.0")
port = int(os.environ.get("APP_PORT", "8080"))
uvicorn.run(app, host=host, port=port, log_level="info")
if __name__ == "__main__":
main()
+29
View File
@@ -0,0 +1,29 @@
"""Хеширование паролей (Argon2id) и генерация opaque-токенов сессий."""
import hashlib
import secrets
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
_hasher = PasswordHasher()
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password_hash: str, password: str) -> bool:
try:
return _hasher.verify(password_hash, password)
except (VerifyMismatchError, VerificationError, InvalidHashError):
return False
def new_token() -> str:
"""256 бит энтропии, URL-safe."""
return secrets.token_urlsafe(32)
def token_hash(token: str) -> str:
"""В БД/Redis храним только SHA-256 от токена, не сам токен."""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
# Перезапускает API и все используемые хранилища, сохраняя volumes.
# Не выполняет down -v, не flush-ит Redis, не пересоздаёт данные.
docker compose restart api postgres redis
# Ждём готовности API (тест сам ждёт /health/ready, но полезно и здесь).
i=0
while [ "$i" -lt 60 ]; do
if docker compose exec -T api python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status==200 else 1)" >/dev/null 2>&1; then
exit 0
fi
i=$((i+1))
sleep 1
done
echo "api did not become ready" >&2
exit 1