diff --git a/.env.example b/.env.example index b70f95ae..e2c535d8 100644 --- a/.env.example +++ b/.env.example @@ -6,6 +6,6 @@ APP_ENV=lab SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL=postgresql://user:password@localhost:5432/high_load_messenger -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres +REDIS_URL=redis://redis:6379/0 # пароль не задан: Redis доступен только внутри compose-сети (порт наружу не публикуется) +SESSION_STORE=redis CACHE_URL_FILE=/run/secrets/cache_url diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..252b1b95 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,46 @@ +x-lab-number: 2 +x-required-roles: + - api + # - postgres + +# Лабораторная 2. API + Redis +services: + redis: + image: redis:7.4.1-alpine + container_name: mtusi-redis + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec", "--save", "60", "1"] + ports: + - "127.0.0.1:6379:6379" + volumes: + - redis-data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + restart: unless-stopped + + api: + build: . + image: mtusi-messenger:lab2 + container_name: mtusi-messenger-lab2 + ports: + - "127.0.0.1:8080:8080" + env_file: + - .env + extra_hosts: + - "host.docker.internal:host-gateway" + depends_on: + redis: + condition: service_healthy + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready').read()"] + interval: 10s + timeout: 3s + retries: 5 + start_period: 10s + restart: unless-stopped + +volumes: + redis-data: \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 3c3be538..87f44179 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,6 @@ fastapi==0.115.0 uvicorn[standard]==0.32.0 psycopg[binary]==3.2.3 +psycopg_pool==3.2.3 +redis==5.2.0 openapi-spec-validator==0.7.2 \ No newline at end of file diff --git a/src/app/api/health.py b/src/app/api/health.py index e407bee2..913a3d25 100644 --- a/src/app/api/health.py +++ b/src/app/api/health.py @@ -1,5 +1,7 @@ -from fastapi import APIRouter +from fastapi import APIRouter, Response from ..models.schemas import Health +from ..storage import db as _db +from ..storage.sessions import _redis_client, _store router = APIRouter(tags=["health"]) @@ -20,6 +22,19 @@ def liveness() -> Health: summary="Проверка готовности принимать трафик", response_model=Health, ) -def readiness() -> Health: - """Готов принимать трафик. В lab1 критичных зависимостей нет.""" +def readiness(response: Response) -> Health: + """200, если PostgreSQL и (в режиме redis) Redis доступны; иначе 503.""" + try: + with _db.connection() as conn, conn.cursor() as cur: + cur.execute("SELECT 1") + cur.fetchone() + except Exception: + response.status_code = 503 + return Health(status="ok") + if _store() == "redis": + try: + _redis_client().ping() + except Exception: + response.status_code = 503 + return Health(status="ok") return Health(status="ok") \ No newline at end of file diff --git a/src/app/api/messages.py b/src/app/api/messages.py index 2449112c..d6350726 100644 --- a/src/app/api/messages.py +++ b/src/app/api/messages.py @@ -1,5 +1,6 @@ import base64 import json +from datetime import datetime from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Query from ..models.schemas import CreateMessage, Message, MessagePage, User @@ -27,7 +28,7 @@ def _decode_cursor(chat_id: UUID, cursor: str) -> tuple: data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode()) if data.get("chat_id") != str(chat_id): raise ValueError("cursor_chat_mismatch") - return UUID(data["id"]), data["created_at"] + return datetime.fromisoformat(data["created_at"]), UUID(data["id"]) except Exception: raise HTTPException(status_code=400, detail="invalid_request") @@ -60,13 +61,12 @@ def list_messages( limit: int = Query(50, ge=1, le=100), cursor: str | None = None, ) -> MessagePage: - """Реализована курсорная пагинация""" - + """Keyset-пагинация в SQL: (created_at, id) по возрастанию, без полного scan истории.""" _require_member(chat_id, user.id) - messages = storage.list_messages(chat_id) - if cursor: - mid, mcreated = _decode_cursor(chat_id, cursor) - messages = [m for m in messages if (m.created_at.isoformat(), str(m.id)) > (mcreated, str(mid))] - page = messages[:limit] - next_cursor = _encode_cursor(chat_id, page[-1]) if len(messages) > limit else None - return MessagePage(items=page, next_cursor=next_cursor) \ No newline at end of file + after = _decode_cursor(chat_id, cursor) if cursor else None + # Берём limit+1, чтобы понять, есть ли следующая страница + rows = storage.list_messages_page(chat_id, limit + 1, after=after) + has_more = len(rows) > limit + items = rows[:limit] + next_cursor = _encode_cursor(chat_id, items[-1]) if has_more and items else None + return MessagePage(items=items, next_cursor=next_cursor) \ No newline at end of file diff --git a/src/app/main.py b/src/app/main.py index ee9c2bdf..d4eea528 100644 --- a/src/app/main.py +++ b/src/app/main.py @@ -10,9 +10,10 @@ from fastapi.exceptions import RequestValidationError from fastapi.openapi.utils import get_openapi from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException +import psycopg import uvicorn from .api import auth, chats, health, messages, users -from .storage.db import init_schema +from .storage.db import init_schema, init_pool, close_pool # --- Логирование: структурированный stdout, без содержимого сообщений --- @@ -26,9 +27,15 @@ logger = logging.getLogger("app") @asynccontextmanager async def lifespan(app: FastAPI): - init_schema() # создать таблицы в БД если их ещё нет - logger.info("event=startup app_env=%s", os.environ.get("APP_ENV", "lab")) + init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4) + init_schema() # создать таблицы в БД если их ещё нет + logger.info( + "event=startup app_env=%s session_store=%s", + os.environ.get("APP_ENV", "lab"), + os.environ.get("SESSION_STORE", "postgres"), + ) yield + close_pool() logger.info("event=shutdown_complete") @@ -121,6 +128,39 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE return _error_response(400, "Неверный запрос", request_id, request.url.path) +@app.exception_handler(psycopg.OperationalError) +async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError): + """PostgreSQL недоступен → 503 unavailable, без внутренних деталей.""" + request_id = getattr(request.state, "request_id", uuid.uuid4().hex) + logger.error( + "event=db_unavailable type=%s request_id=%s", + type(exc).__name__, + request_id, + ) + return _error_response(503, "Зависимость недоступна", request_id, request.url.path) + + +@app.exception_handler(RuntimeError) +async def runtime_error_handler(request: Request, exc: RuntimeError): + """Redis недоступен или конфигурация битая. + + sessions.py поднимает RuntimeError("redis_unavailable") при ошибке Redis. + Отдаём 503, чтобы смоук/resilience видели корректный unavailable, + а не внутреннюю 500. + """ + request_id = getattr(request.state, "request_id", uuid.uuid4().hex) + text = str(exc) + if "redis_unavailable" in text: + logger.error("event=redis_unavailable request_id=%s", request_id) + return _error_response(503, "Зависимость недоступна", request_id, request.url.path) + logger.error( + "event=runtime_error type=%s request_id=%s", + type(exc).__name__, + request_id, + ) + return _error_response(500, "Внутренняя ошибка", request_id, request.url.path) + + @app.exception_handler(Exception) async def unhandled_exception_handler(request: Request, exc: Exception): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) diff --git a/src/app/storage/db.py b/src/app/storage/db.py index 40be8902..4dbaabb2 100644 --- a/src/app/storage/db.py +++ b/src/app/storage/db.py @@ -3,6 +3,10 @@ from contextlib import contextmanager from typing import Iterator import psycopg +from psycopg_pool import ConnectionPool + + +_pool: ConnectionPool | None = None def _dsn() -> str: @@ -12,14 +16,37 @@ def _dsn() -> str: return dsn +def init_pool() -> None: + """Ограниченный пул соединений с таймаутами. Вызывается один раз на старте.""" + global _pool + if _pool is not None: + return + _pool = ConnectionPool( + conninfo=_dsn(), + min_size=2, + max_size=10, + timeout=5.0, + max_idle=300.0, + kwargs={"options": "-c statement_timeout=5000"}, + open=True, + ) + + +def close_pool() -> None: + global _pool + if _pool is not None: + _pool.close() + _pool = None + + @contextmanager def connection() -> Iterator[psycopg.Connection]: - """Одно соединение на запрос; autocommit=False для явных транзакций.""" - conn = psycopg.connect(_dsn()) - try: + """Соединение из пула; autocommit=False для явных транзакций.""" + if _pool is None: + init_pool() + assert _pool is not None + with _pool.connection() as conn: yield conn - finally: - conn.close() SCHEMA_SQL = """ @@ -53,6 +80,7 @@ CREATE TABLE IF NOT EXISTS messages ( CREATE INDEX IF NOT EXISTS idx_messages_chat_created ON messages (chat_id, created_at, id); +-- sessions остаются как fallback, если SESSION_STORE=postgres. CREATE TABLE IF NOT EXISTS sessions ( token TEXT PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, diff --git a/src/app/storage/postgres.py b/src/app/storage/postgres.py index 8f6f4a4d..114bf96e 100644 --- a/src/app/storage/postgres.py +++ b/src/app/storage/postgres.py @@ -2,12 +2,17 @@ import hashlib import hmac import secrets import threading -from datetime import datetime, timedelta, timezone +from datetime import datetime, timezone from typing import List, Optional from uuid import UUID, uuid4 from ..models.schemas import Chat, Message, User from .db import connection +from .sessions import ( + create_session as _sess_create, + get_session_user as _sess_get, + revoke_session as _sess_revoke, +) def now_utc() -> datetime: @@ -74,6 +79,8 @@ class PostgresStorage: def create_user(self, username: str, display_name: str, password: str) -> User: with self._lock, connection() as conn: with conn.cursor() as cur: + # SELECT-проверка + INSERT в одной транзакции; уникальный индекс + # users.username отсекает гонку на уровне БД (UniqueViolation). cur.execute("SELECT 1 FROM users WHERE username = %s", (username,)) if cur.fetchone() is not None: raise ValueError("username_taken") @@ -81,12 +88,19 @@ class PostgresStorage: id=uuid4(), username=username, display_name=display_name, created_at=now_utc(), ) - cur.execute( - "INSERT INTO users (id, username, display_name, password_hash, created_at)" - " VALUES (%s, %s, %s, %s, %s)", - (user.id, user.username, user.display_name, - _hash_password(password), user.created_at), - ) + try: + cur.execute( + "INSERT INTO users (id, username, display_name, password_hash, created_at)" + " VALUES (%s, %s, %s, %s, %s)", + (user.id, user.username, user.display_name, + _hash_password(password), user.created_at), + ) + except Exception as exc: + # Параллельная регистрация того же username: уникальный индекс + # выбросил UniqueViolation — превращаем в доменную ошибку. + if exc.__class__.__name__ == "UniqueViolation": + raise ValueError("username_taken") + raise conn.commit() return user @@ -122,42 +136,17 @@ class PostgresStorage: return None return _row_to_user(row[:4]) - # ---------- Сессии ---------- + # ---------- Сессии (Redis или PostgreSQL — см. storage/sessions.py) ---------- + # Тонкие делегаты: роутеры продолжают вызывать storage.create_session(...), + # storage.get_session_user(...), storage.revoke_session(...) без изменений. def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple: - token = secrets.token_urlsafe(32) - expires_at = now_utc() + timedelta(seconds=ttl_seconds) - with self._lock, connection() as conn: - with conn.cursor() as cur: - cur.execute( - "INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)", - (token, user_id, expires_at), - ) - conn.commit() - return token, expires_at + return _sess_create(user_id, ttl_seconds) def get_session_user(self, token: str) -> Optional[User]: - with connection() as conn, conn.cursor() as cur: - cur.execute( - "SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at" - " FROM sessions s JOIN users u ON u.id = s.user_id" - " WHERE s.token = %s", - (token,), - ) - row = cur.fetchone() - if row is None: - return None - if row[4] <= now_utc(): - with conn.cursor() as cur2: - cur2.execute("DELETE FROM sessions WHERE token = %s", (token,)) - conn.commit() - return None - return _row_to_user(row[:4]) + return _sess_get(token) def revoke_session(self, token: str) -> None: - with self._lock, connection() as conn: - with conn.cursor() as cur: - cur.execute("DELETE FROM sessions WHERE token = %s", (token,)) - conn.commit() + _sess_revoke(token) # ---------- Чаты ---------- def create_chat(self, title: str, member_ids: List[UUID]) -> Chat: @@ -245,5 +234,34 @@ class PostgresStorage: ) return [_row_to_message(r) for r in cur.fetchall()] + def list_messages_page( + self, + chat_id: UUID, + limit: int, + after: Optional[tuple] = None, + ) -> List[Message]: + """Keyset-пагинация в SQL + + after = (created_at, id) последней записи предыдущей страницы или None. + Запрос использует индекс idx_messages_chat_created (chat_id, created_at, id) + и не делает полный scan всей истории на каждую страницу. + """ + with connection() as conn, conn.cursor() as cur: + if after is None: + cur.execute( + "SELECT id, chat_id, sender_id, text, created_at FROM messages" + " WHERE chat_id = %s ORDER BY created_at, id LIMIT %s", + (chat_id, limit), + ) + else: + after_ts, after_id = after + cur.execute( + "SELECT id, chat_id, sender_id, text, created_at FROM messages" + " WHERE chat_id = %s AND (created_at, id) > (%s, %s)" + " ORDER BY created_at, id LIMIT %s", + (chat_id, after_ts, after_id, limit), + ) + return [_row_to_message(r) for r in cur.fetchall()] + storage = PostgresStorage() # единственный экземпляр на процесс \ No newline at end of file diff --git a/student-tests/test_lab2_level4.py b/student-tests/test_lab2_level4.py new file mode 100644 index 00000000..f85a0f37 --- /dev/null +++ b/student-tests/test_lab2_level4.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Уровень 4 lab2: конкурентная регистрация, expiry TTL, недоступность Redis, EXPLAIN.""" +import base64 +import os +import subprocess +import sys +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client, Failure, arguments, check, run # noqa: E402 + + +def test_concurrent_registration(c): + """Один и тот же username с 8 потоков — ровно одна 201, остальные 409.""" + username = "race_" + uuid.uuid4().hex[:10] + password = "T3st-" + uuid.uuid4().hex + body = {"username": username, "display_name": "Race", "password": password} + results = [] + lock = __import__("threading").Lock() + + def one(_): + local = Client(c.base, timeout=10) + try: + local.call("POST", "/api/v1/users", 201, body=body) + with lock: + results.append(201) + except Failure: + with lock: + results.append(409) + + with ThreadPoolExecutor(max_workers=8) as pool: + list(pool.map(one, range(8))) + check(results.count(201) == 1, "expected exactly one 201, got %s" % results) + check(results.count(409) == 7, "expected seven 409, got %s" % results) + + +def test_short_ttl_expiry(c, base_url): + """Регистрация + сессия с TTL=2с; через 4с токен недействителен.""" + suffix = uuid.uuid4().hex[:10] + username = "ttl_" + suffix + password = "T3st-" + uuid.uuid4().hex + c.call("POST", "/api/v1/users", 201, + body={"username": username, "display_name": "TTL", "password": password}) + cred = base64.b64encode((username + ":" + password).encode()).decode() + session = c.call("POST", "/api/v1/auth/sessions", 201, + headers={"Authorization": "Basic " + cred})["json"] + # Работает сразу + c.call("GET", "/api/v1/users/me", 200, + headers={"Authorization": "Bearer " + session["token"]}) + # Ждём больше TTL + time.sleep(4) + c.call("GET", "/api/v1/users/me", 401, + headers={"Authorization": "Bearer " + session["token"]}) + + +def test_redis_unavailable(c, base_url): + """Останавливаем Redis — /health/ready отдаёт 503, Bearer не проходит.""" + print(" (проверка недоступности Redis: docker stop mtusi-redis на 5 секунд)") + r = subprocess.run(["docker", "stop", "mtusi-redis"], capture_output=True, text=True, timeout=30) + check(r.returncode == 0, "cannot stop Redis container") + try: + time.sleep(3) + ready = c.call("GET", "/health/ready", 503) + check(ready["status"] == 503, "readiness must be 503 without Redis") + c.call("GET", "/api/v1/users/me", 401, + headers={"Authorization": "Bearer " + "x" * 43}) + finally: + subprocess.run(["docker", "start", "mtusi-redis"], capture_output=True, text=True, timeout=30) + time.sleep(4) + c.call("GET", "/health/ready", 200) + + +def test_explain(c): + """EXPLAIN (ANALYZE, BUFFERS) по запросу истории — индекс используется.""" + # Просим psql через docker exec выполнить EXPLAIN. + sql = ( + "EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at " + "FROM messages WHERE chat_id = (SELECT chat_id FROM messages LIMIT 1) " + "ORDER BY created_at, id LIMIT 51;" + ) + r = subprocess.run( + ["docker", "exec", "-i", "mtusi-messenger-lab2", "python", "-c", + "import os,psycopg;conn=psycopg.connect(os.environ['DATABASE_URL']);" + "cur=conn.cursor();cur.execute(%r);" + "print('\\n'.join(row[0] for row in cur.fetchall()))" % sql], + capture_output=True, text=True, timeout=30, + ) + out = r.stdout + r.stderr + check("Index" in out or "Bitmap Index" in out or "idx_messages_chat_created" in out, + "EXPLAIN не показал использование индекса:\n" + out) + print("EXPLAIN (фрагмент):") + for line in out.splitlines()[:8]: + print(" ", line) + + +def main(): + args = arguments("Lab2 level 4 checks") + c = Client(args.base_url, args.ca_file) + print("=== test_concurrent_registration ===") + test_concurrent_registration(c) + print("PASS: concurrent registration produces exactly one user") + print("=== test_short_ttl_expiry ===") + test_short_ttl_expiry(c, args.base_url) + print("PASS: session expires after SESSION_TTL_SECONDS") + print("=== test_explain ===") + test_explain(c) + print("PASS: EXPLAIN uses idx_messages_chat_created") + print("=== test_redis_unavailable ===") + test_redis_unavailable(c, args.base_url) + print("PASS: readiness 503 без Redis, затем восстановление") + print("PASS: all lab2 level-4 checks passed") + + +if __name__ == "__main__": + run(main) \ No newline at end of file