diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 00000000..1aab4e3b --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +"""MTUSI Messenger — лабораторная 2: PostgreSQL, сессии и Redis-кэш.""" diff --git a/app/db.py b/app/db.py new file mode 100644 index 00000000..a7213b6c --- /dev/null +++ b/app/db.py @@ -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,) + ) diff --git a/app/errors.py b/app/errors.py new file mode 100644 index 00000000..3ea7b2ca --- /dev/null +++ b/app/errors.py @@ -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}} diff --git a/app/main.py b/app/main.py new file mode 100644 index 00000000..ab2aac61 --- /dev/null +++ b/app/main.py @@ -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() diff --git a/app/security.py b/app/security.py new file mode 100644 index 00000000..b5ff1562 --- /dev/null +++ b/app/security.py @@ -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() diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..dc2d3d24 --- /dev/null +++ b/scripts/restart.sh @@ -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