diff --git a/.env.example b/.env.example index 714c8076..f4266ba1 100644 --- a/.env.example +++ b/.env.example @@ -4,6 +4,7 @@ APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab SESSION_TTL_SECONDS=3600 +CACHE_TTL_SECONDS=60 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url # Optional on 3, required use on 4 in lab2; Redis OR Valkey: diff --git a/Makefile b/Makefile index 9ecb223e..ffc955ca 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence +.PHONY: help check validate test load test-persistence test-grade4 help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -24,3 +24,7 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-grade4: + $(PYTHON) student-tests/lab4_checks.py + ./scripts/test_dependencies.sh diff --git a/REPORT.md b/REPORT.md index d39a6daa..9ae87dda 100644 --- a/REPORT.md +++ b/REPORT.md @@ -30,6 +30,22 @@ curl -fsS http://localhost:8080/health/ready make test chmod +x scripts/restart.sh make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-grade4 +``` + +Для проверки короткого TTL временно пересоздайте только API: + +```sh +SESSION_TTL_SECONDS=2 docker compose --env-file .env.example up -d --force-recreate api +docker compose --env-file .env.example up -d --wait api +python3 student-tests/session_expiry.py +SESSION_TTL_SECONDS=3600 docker compose --env-file .env.example up -d --force-recreate api +``` + +План запроса истории создаётся на 10 000 синтетических сообщениях: + +```sh +./scripts/explain_history.sh | tee evidence/explain-history-local.txt ``` Обычная остановка сохраняет учебные данные: @@ -74,6 +90,10 @@ Logout удаляет текущую серверную сессию. Срок | Согласованность lock-файла | `uv lock --check` | PASS | выполнено | | Публичный smoke | `make test` | `PASS: lab2 public API scenario` | `evidence/smoke-2026-10-08.txt` | | Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS: persistence preserved confirmed data and existing session` | `evidence/persistence-2026-10-08.txt` | +| Redis cache | `make test-grade4`; `redis-cli --scan` | read-after-write без stale read; создан ключ `history:first:…` | `evidence/redis-cache-2026-10-08.txt` | +| Гонка и rollback | `make test-grade4` | Ровно одна регистрация успешна; неуспешный чат не виден | `evidence/grade4-checks-2026-10-08.txt` | +| TTL и зависимости | `make test-grade4`; TTL=2 | Expired session → 401; Redis fallback проходит smoke; DB readiness → 503 | `evidence/grade4-checks-2026-10-08.txt` | +| Индекс истории | `./scripts/explain_history.sh` | Index Scan, 50 строк, shared hit=3 | `evidence/explain-history-2026-10-08.txt` | ## Ограничения и следующие шаги diff --git a/compose.yaml b/compose.yaml index 4c1eafe4..432240f6 100644 --- a/compose.yaml +++ b/compose.yaml @@ -24,9 +24,12 @@ services: APP_PORT: 8080 APP_ENV: lab2 DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + CACHE_TTL_SECONDS: ${CACHE_TTL_SECONDS:-60} SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} secrets: - database_url + - cache_url depends_on: postgres: condition: service_healthy @@ -39,11 +42,26 @@ services: retries: 12 start_period: 10s + redis: + image: redis:7.4.2-alpine + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + volumes: + - redis_data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 12 + start_period: 5s + secrets: postgres_password: file: ./secrets/postgres_password database_url: file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url volumes: postgres_data: + redis_data: diff --git a/evidence/explain-history-2026-10-08.txt b/evidence/explain-history-2026-10-08.txt new file mode 100644 index 00000000..c4fd493f --- /dev/null +++ b/evidence/explain-history-2026-10-08.txt @@ -0,0 +1,14 @@ +Date: 2026-10-08 +Command: ./scripts/explain_history.sh + +Dataset: 10,000 synthetic messages in one chat. +Query plan: +Limit (cost=0.29..4.20 rows=50 width=73) (actual time=0.006..0.010 rows=50 loops=1) + Buffers: shared hit=3 + -> Index Scan using messages_chat_created_id_idx on messages (cost=0.29..783.39 rows=10000 width=73) (actual time=0.006..0.008 rows=50 loops=1) + Index Cond: (chat_id = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'::uuid) + Buffers: shared hit=3 +Planning: + Buffers: shared hit=39 +Planning Time: 0.099 ms +Execution Time: 0.016 ms diff --git a/evidence/grade4-checks-2026-10-08.txt b/evidence/grade4-checks-2026-10-08.txt new file mode 100644 index 00000000..31162fd3 --- /dev/null +++ b/evidence/grade4-checks-2026-10-08.txt @@ -0,0 +1,11 @@ +Date: 2026-10-08 +Commands: + make test-grade4 + SESSION_TTL_SECONDS=2 docker compose --env-file .env.example up -d --force-recreate api + python3 student-tests/session_expiry.py + +Results: +PASS: registration race, chat rollback and cache read-after-write +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. +PASS: readiness rejects unavailable PostgreSQL +PASS: expired Bearer session was rejected diff --git a/evidence/redis-cache-2026-10-08.txt b/evidence/redis-cache-2026-10-08.txt new file mode 100644 index 00000000..e2301e0e --- /dev/null +++ b/evidence/redis-cache-2026-10-08.txt @@ -0,0 +1,6 @@ +Date: 2026-10-08 +Command: + docker compose exec -T redis redis-cli --scan --pattern 'history:first:*' + +Observed key after public smoke: +history:first:b1805682-25ab-4339-b2f1-6c61ccffbec4:v2:l1 diff --git a/migrations/002_history_cache_version.sql b/migrations/002_history_cache_version.sql new file mode 100644 index 00000000..7b7972c1 --- /dev/null +++ b/migrations/002_history_cache_version.sql @@ -0,0 +1 @@ +ALTER TABLE chats ADD COLUMN history_version bigint NOT NULL DEFAULT 0; diff --git a/pyproject.toml b/pyproject.toml index 2eb0b29d..9de26558 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,5 +8,6 @@ dependencies = [ "argon2-cffi==25.1.0", "asyncpg==0.31.0", "fastapi==0.141.1", + "redis==5.0.8", "uvicorn==0.40.0", ] diff --git a/scripts/explain_history.sh b/scripts/explain_history.sh new file mode 100755 index 00000000..cec693a3 --- /dev/null +++ b/scripts/explain_history.sh @@ -0,0 +1,35 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." + +docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 <<'SQL' +INSERT INTO users (id, username, display_name, password_hash) +VALUES ('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'plan_user', 'Plan user', 'not-used') +ON CONFLICT (id) DO NOTHING; + +INSERT INTO chats (id, title) +VALUES ('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', 'Plan history') +ON CONFLICT (id) DO NOTHING; + +INSERT INTO chat_members (chat_id, user_id) +VALUES ('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa') +ON CONFLICT DO NOTHING; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT + ('00000000-0000-4000-8000-' || lpad(item::text, 12, '0'))::uuid, + 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + 'plan message ' || item, + '2026-01-01T00:00:00Z'::timestamptz + item * interval '1 microsecond' +FROM generate_series(1, 10000) AS item +ON CONFLICT (id) DO NOTHING; + +ANALYZE messages; +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +ORDER BY created_at, id +LIMIT 50; +SQL diff --git a/scripts/restart.sh b/scripts/restart.sh index 5d062916..d29bed84 100755 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -1,4 +1,4 @@ #!/bin/sh set -eu cd "$(dirname "$0")/.." -docker compose restart api postgres +docker compose restart api postgres redis diff --git a/scripts/test_dependencies.sh b/scripts/test_dependencies.sh new file mode 100755 index 00000000..41c6936c --- /dev/null +++ b/scripts/test_dependencies.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." + +restore() { + docker compose start postgres redis >/dev/null 2>&1 || true + docker compose up -d --wait api >/dev/null 2>&1 || true +} +trap restore EXIT + +docker compose stop redis +make test +docker compose start redis +docker compose up -d --wait api +docker compose stop postgres +python3 student-tests/readiness_unavailable.py diff --git a/src/config.py b/src/config.py index 80aa98f0..61d26192 100644 --- a/src/config.py +++ b/src/config.py @@ -10,6 +10,9 @@ _CONFIGURATION_KEYS = { "APP_ENV", "DATABASE_URL", "DATABASE_URL_FILE", + "CACHE_URL", + "CACHE_URL_FILE", + "CACHE_TTL_SECONDS", "SESSION_TTL_SECONDS", } @@ -23,6 +26,8 @@ class Settings: environment: str database_url: str session_ttl_seconds: int + cache_url: str | None + cache_ttl_seconds: int def load_settings(env_file: Path = ROOT / ".env") -> Settings: @@ -68,10 +73,27 @@ def load_settings(env_file: Path = ROOT / ".env") -> Settings: raise ValueError("SESSION_TTL_SECONDS должен быть целым числом") from error if session_ttl_seconds < 1: raise ValueError("SESSION_TTL_SECONDS должен быть положительным") + cache_url_file = os.environ.get("CACHE_URL_FILE", "").strip() + cache_url = os.environ.get("CACHE_URL", "").strip() + if cache_url_file: + try: + cache_url = Path(cache_url_file).read_text(encoding="utf-8").strip() + except OSError as error: + raise ValueError("CACHE_URL_FILE недоступен") from error + if cache_url and not cache_url.startswith(("redis://", "rediss://")): + raise ValueError("CACHE_URL должен содержать Redis URL") + try: + cache_ttl_seconds = int(os.environ.get("CACHE_TTL_SECONDS", "60")) + except ValueError as error: + raise ValueError("CACHE_TTL_SECONDS должен быть целым числом") from error + if cache_ttl_seconds < 1: + raise ValueError("CACHE_TTL_SECONDS должен быть положительным") return Settings( host=host, port=port, environment=environment, database_url=database_url, session_ttl_seconds=session_ttl_seconds, + cache_url=cache_url or None, + cache_ttl_seconds=cache_ttl_seconds, ) diff --git a/src/main.py b/src/main.py index 46fb8e87..3e60da5b 100644 --- a/src/main.py +++ b/src/main.py @@ -13,6 +13,7 @@ from .errors import ApiError from .models import ErrorDetails, ErrorResponse from .config import load_settings from .routes import router +from .storage.history_cache import HistoryCache from .storage.postgres import PostgresStore @@ -35,9 +36,13 @@ async def lifespan(application: FastAPI): await store.migrate() application.state.store = store application.state.settings = settings + cache = HistoryCache(settings.cache_url, settings.cache_ttl_seconds) + await cache.connect() + application.state.history_cache = cache try: yield finally: + await cache.close() await store.close() diff --git a/src/routes.py b/src/routes.py index c2062e9c..e0378ca8 100644 --- a/src/routes.py +++ b/src/routes.py @@ -8,6 +8,7 @@ from .cursor import CursorError, decode_cursor, encode_cursor from .errors import ApiError from .models import Chat, ChatPageResponse, CreateChatRequest, CreateMessageRequest, CreateUserRequest, Message, MessagePageResponse, Session, User from .storage.postgres import PostgresStore +from .storage.history_cache import HistoryCache router = APIRouter() BEARER_CHALLENGE = {'WWW-Authenticate': 'Bearer realm="messenger"'} @@ -16,6 +17,9 @@ BASIC_CHALLENGE = {'WWW-Authenticate': 'Basic realm="messenger", charset="UTF-8" def get_store(request: Request) -> PostgresStore: return request.app.state.store +def get_history_cache(request: Request) -> HistoryCache: + return request.app.state.history_cache + async def get_current_user(authorization: str | None = Header(default=None), store: PostgresStore = Depends(get_store)) -> dict: if authorization is None or not authorization.startswith("Bearer "): raise ApiError(401, "unauthorized", "Требуется Bearer-сессия", BEARER_CHALLENGE) @@ -99,10 +103,11 @@ async def get_chat(chat_id: UUID, user: dict = Depends(get_current_user), store: @router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201) async def create_message(chat_id: UUID, payload: CreateMessageRequest, user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)) -> dict: - return await store.create_message(chat_id, user["id"], payload.text) + message, _version = await store.create_message(chat_id, user["id"], payload.text) + return message @router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePageResponse) -async def list_messages(chat_id: UUID, user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store), limit: int = Query(default=50, ge=1, le=100), cursor: str | None = Query(default=None, min_length=1)) -> MessagePageResponse: +async def list_messages(chat_id: UUID, user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store), cache: HistoryCache = Depends(get_history_cache), limit: int = Query(default=50, ge=1, le=100), cursor: str | None = Query(default=None, min_length=1)) -> MessagePageResponse: after: tuple[datetime, UUID] | None = None scope = "messages:" + str(chat_id) if cursor is not None: @@ -111,7 +116,14 @@ async def list_messages(chat_id: UUID, user: dict = Depends(get_current_user), s after = created_at, UUID(item_id) except (CursorError, ValueError) as error: raise ApiError(400, "invalid_request", "Некорректный cursor") from error - rows = await store.list_messages_for_member(chat_id, user["id"], after, limit) + if cursor is None: + version = await store.history_version_for_member(chat_id, user["id"]) + rows = await cache.get(chat_id, version, limit) + if rows is None: + rows = await store.list_messages_for_member(chat_id, user["id"], after, limit) + await cache.set(chat_id, version, limit, rows) + else: + rows = await store.list_messages_for_member(chat_id, user["id"], after, limit) page = rows[:limit] next_cursor = encode_cursor(scope, page[-1]["created_at"], str(page[-1]["id"])) if len(rows) > limit else None return MessagePageResponse(items=page, next_cursor=next_cursor) diff --git a/src/storage/history_cache.py b/src/storage/history_cache.py new file mode 100644 index 00000000..b3803f43 --- /dev/null +++ b/src/storage/history_cache.py @@ -0,0 +1,60 @@ +import json +from uuid import UUID + +from redis.asyncio import Redis +from redis.exceptions import RedisError + + +class HistoryCache: + """Кэш только первой страницы истории; PostgreSQL остаётся источником истины.""" + + def __init__(self, url: str | None, ttl_seconds: int) -> None: + self._url = url + self._ttl_seconds = ttl_seconds + self._client: Redis | None = None + self._disabled = not bool(url) + + async def connect(self) -> None: + if self._disabled: + return + try: + client = Redis.from_url( + self._url, + decode_responses=True, + socket_connect_timeout=1, + socket_timeout=1, + max_connections=10, + ) + await client.ping() + self._client = client + except RedisError: + self._disabled = True + + async def close(self) -> None: + if self._client is not None: + await self._client.aclose() + + @staticmethod + def _key(chat_id: UUID, version: int, limit: int) -> str: + return f"history:first:{chat_id}:v{version}:l{limit}" + + async def get(self, chat_id: UUID, version: int, limit: int) -> list[dict] | None: + if self._disabled or self._client is None: + return None + try: + value = await self._client.get(self._key(chat_id, version, limit)) + return json.loads(value) if value else None + except (RedisError, ValueError, TypeError): + self._disabled = True + return None + + async def set(self, chat_id: UUID, version: int, limit: int, items: list[dict]) -> None: + if self._disabled or self._client is None: + return + try: + encoded = json.dumps(items, default=str, separators=(",", ":")) + await self._client.set( + self._key(chat_id, version, limit), encoded, ex=self._ttl_seconds + ) + except RedisError: + self._disabled = True diff --git a/src/storage/postgres.py b/src/storage/postgres.py index ad3367e5..435c2f05 100644 --- a/src/storage/postgres.py +++ b/src/storage/postgres.py @@ -26,7 +26,7 @@ class PostgresStore: self._pool = await asyncpg.create_pool( self._database_url, min_size=1, max_size=10, command_timeout=5 ) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise RuntimeError("PostgreSQL is unavailable") from error async def close(self) -> None: @@ -87,7 +87,7 @@ class PostgresStore: async def ready(self) -> None: try: await self.pool.fetchval("SELECT 1") - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error async def create_user(self, username: str, display_name: str, password: str) -> dict: @@ -101,7 +101,7 @@ class PostgresStore: ) except asyncpg.UniqueViolationError as error: raise ApiError(409, "conflict", "Username уже занят") from error - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return self._user(row) @@ -110,7 +110,7 @@ class PostgresStore: row = await self.pool.fetchrow( "SELECT id, username, display_name, created_at FROM users WHERE id = $1", user_id ) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return self._user(row) if row else None @@ -120,7 +120,7 @@ class PostgresStore: "SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1", username, ) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error if row is None: return None @@ -140,7 +140,7 @@ class PostgresStore: user["id"], ttl_seconds, ) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return {"token": token, "token_type": "Bearer", "expires_at": row["expires_at"], "user": user} @@ -151,7 +151,7 @@ class PostgresStore: "SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now()", token_hash, ) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return self._user(row) if row else None @@ -160,7 +160,7 @@ class PostgresStore: await self.pool.execute( "DELETE FROM sessions WHERE token_hash = $1", sha256(token.encode("ascii")).hexdigest() ) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error async def create_chat(self, creator_id: UUID, title: str, member_ids: list[UUID]) -> dict: @@ -182,7 +182,7 @@ class PostgresStore: "INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", [(row["id"], member_id) for member_id in member_ids], ) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return { "id": row["id"], @@ -198,7 +198,7 @@ class PostgresStore: chat_id, user_id, ) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error if row is None: raise ApiError(404, "not_found", "Чат не найден") @@ -216,23 +216,47 @@ class PostgresStore: args.append(limit + 1) try: rows = await self.pool.fetch(query, *args) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return [self._chat(row) for row in rows] async def create_message(self, chat_id: UUID, sender_id: UUID, text: str) -> dict: - await self.get_chat_for_member(chat_id, sender_id) try: - row = await self.pool.fetchrow( - "INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at", - uuid4(), - chat_id, - sender_id, - text, - ) - except asyncpg.PostgresError as error: + async with self.pool.acquire() as connection, connection.transaction(): + member = await connection.fetchval( + "SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", + chat_id, + sender_id, + ) + if member is None: + raise ApiError(404, "not_found", "Чат не найден") + row = await connection.fetchrow( + "INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at", + uuid4(), + chat_id, + sender_id, + text, + ) + version = await connection.fetchval( + "UPDATE chats SET history_version = history_version + 1 WHERE id = $1 RETURNING history_version", + chat_id, + ) + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error - return self._message(row) + return self._message(row), version + + async def history_version_for_member(self, chat_id: UUID, user_id: UUID) -> int: + try: + version = await self.pool.fetchval( + "SELECT c.history_version FROM chats c JOIN chat_members cm ON cm.chat_id = c.id WHERE c.id = $1 AND cm.user_id = $2", + chat_id, + user_id, + ) + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: + raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error + if version is None: + raise ApiError(404, "not_found", "Чат не найден") + return version async def list_messages_for_member( self, chat_id: UUID, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int @@ -247,6 +271,6 @@ class PostgresStore: args.append(limit + 1) try: rows = await self.pool.fetch(query, *args) - except asyncpg.PostgresError as error: + except (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return [self._message(row) for row in rows] diff --git a/student-tests/lab4_checks.py b/student-tests/lab4_checks.py new file mode 100644 index 00000000..0df37ed8 --- /dev/null +++ b/student-tests/lab4_checks.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Проверки гонки регистрации и rollback создания чата.""" +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import sys +import uuid + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client, check, run # noqa: E402 + + +def main() -> None: + client = Client() + alice, bob, _eve, chat = client.bootstrap() + + username = "race_" + uuid.uuid4().hex[:12] + body = { + "username": username, + "display_name": "Гонка регистрации", + "password": "Race-password-" + uuid.uuid4().hex, + } + + def register_once() -> int: + local = Client() + return local.call("POST", "/api/v1/users", expected=[201, 409], body=body)["status"] + + with ThreadPoolExecutor(max_workers=8) as pool: + statuses = list(pool.map(lambda _unused: register_once(), range(8))) + check(statuses.count(201) == 1 and statuses.count(409) == 7, "username race was not serialized") + + title = "rollback-" + uuid.uuid4().hex + client.call( + "POST", + "/api/v1/chats", + 400, + actor=alice, + body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]}, + ) + chats = client.call( + "GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage" + )["json"]["items"] + check(all(chat["title"] != title for chat in chats), "failed chat creation left a chat") + + first = client.message(alice, chat, "before cached read")["json"] + client.call( + "GET", + "/api/v1/chats/" + chat["id"] + "/messages?limit=100", + actor=alice, + schema="MessagePage", + ) + second = client.message(bob, chat, "after cached read")["json"] + history = client.call( + "GET", + "/api/v1/chats/" + chat["id"] + "/messages?limit=100", + actor=alice, + schema="MessagePage", + )["json"]["items"] + check( + {message["id"] for message in history} == {first["id"], second["id"]}, + "history cache returned stale data after write", + ) + print("PASS: registration race, chat rollback and cache read-after-write") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/readiness_unavailable.py b/student-tests/readiness_unavailable.py new file mode 100644 index 00000000..cf4bffa1 --- /dev/null +++ b/student-tests/readiness_unavailable.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +"""Проверка 503 readiness при остановленном PostgreSQL.""" +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client, run # noqa: E402 + + +def main() -> None: + Client().call("GET", "/health/ready", 503) + print("PASS: readiness rejects unavailable PostgreSQL") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/session_expiry.py b/student-tests/session_expiry.py new file mode 100644 index 00000000..37e29fb8 --- /dev/null +++ b/student-tests/session_expiry.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Проверка expiry; запускается при SESSION_TTL_SECONDS=2.""" +from pathlib import Path +import sys +import time + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client, check, run # noqa: E402 + + +def main() -> None: + client = Client() + actor = client.user("expiry") + time.sleep(3) + client.call("GET", "/api/v1/users/me", 401, actor=actor) + print("PASS: expired Bearer session was rejected") + + +if __name__ == "__main__": + run(main) diff --git a/uv.lock b/uv.lock index c5c450d3..d45c8ed1 100644 --- a/uv.lock +++ b/uv.lock @@ -268,6 +268,7 @@ dependencies = [ { name = "argon2-cffi" }, { name = "asyncpg" }, { name = "fastapi" }, + { name = "redis" }, { name = "uvicorn" }, ] @@ -276,6 +277,7 @@ requires-dist = [ { name = "argon2-cffi", specifier = "==25.1.0" }, { name = "asyncpg", specifier = "==0.31.0" }, { name = "fastapi", specifier = "==0.141.1" }, + { name = "redis", specifier = "==5.0.8" }, { name = "uvicorn", specifier = "==0.40.0" }, ] @@ -378,6 +380,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fa/04/c81d4841331c2178b6fb09ae225425e110ed72d990c9fe556c4ec03d1013/pydantic_core-2.46.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e24d8f05fa2d28513d94e877e9c75ad66175376209b3977f916e240e623193c", size = 2111034, upload-time = "2026-08-28T10:01:07.345Z" }, ] +[[package]] +name = "redis" +version = "5.0.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/48/10/defc227d65ea9c2ff5244645870859865cba34da7373477c8376629746ec/redis-5.0.8.tar.gz", hash = "sha256:0c5b10d387568dfe0698c6fad6615750c24170e548ca2deac10c649d463e9870", size = 4595651, upload-time = "2024-07-30T14:11:52.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/d1/19a9c76811757684a0f74adc25765c8a901d67f9f6472ac9d57c844a23c8/redis-5.0.8-py3-none-any.whl", hash = "sha256:56134ee08ea909106090934adc36f65c9bcbbaecea5b21ba704ba6fb561f8eb4", size = 255608, upload-time = "2024-07-30T14:11:49.541Z" }, +] + [[package]] name = "starlette" version = "1.7.0"