From 752995515f1bbef23c14c6d1226b2352646f07fe Mon Sep 17 00:00:00 2001 From: lolochka132 Date: Sun, 22 Nov 2026 16:11:18 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=203:=20=D1=80=D0=B5=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD=20=D1=81=D1=82=D0=B5=D0=BD?= =?UTF-8?q?=D0=B4=20=D1=81=20=D0=B1=D0=B0=D0=BB=D0=B0=D0=BD=D1=81=D0=B8?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D1=89=D0=B8=D0=BA=D0=BE=D0=BC=20=D0=B8=20?= =?UTF-8?q?=D0=B8=D0=B4=D0=B5=D0=BC=D0=BF=D0=BE=D1=82=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=BD=D0=BE=D1=81=D1=82=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/pull_request_template.md | 14 +- Dockerfile | 34 ++ Makefile | 11 +- REPORT.md | 59 +++- app/__init__.py | 2 + app/config.py | 19 + app/db.py | 302 ++++++++++++++++ app/errors.py | 29 ++ app/main.py | 411 ++++++++++++++++++++++ app/migrate.py | 67 ++++ app/migrations/001_init.sql | 58 +++ compose.yaml | 121 +++++++ evidence/scale/experiment.json | 9 + evidence/scale/fixed-1-replicas.json | 17 + evidence/scale/fixed-2-replicas.json | 17 + evidence/scale/fixed-4-replicas.json | 17 + evidence/scale/resources-1cpu-512mb.json | 17 + evidence/scale/resources-2cpu-1024mb.json | 17 + evidence/scale/resources-4cpu-2048mb.json | 17 + infra/haproxy.cfg | 39 ++ requirements.txt | 5 + scripts/benchmark_scale.py | 80 +++++ scripts/restart.bat | 6 + scripts/restart.py | 24 ++ scripts/restart.sh | 12 + scripts/rolling_update.py | 44 +++ scripts/scale_topology.py | 65 ++++ scripts/stop-one.bat | 9 + scripts/stop-one.py | 25 ++ scripts/stop-one.sh | 12 + tests/concurrent_idempotency.py | 40 +++ 31 files changed, 1576 insertions(+), 23 deletions(-) create mode 100644 Dockerfile create mode 100644 app/__init__.py create mode 100644 app/config.py create mode 100644 app/db.py create mode 100644 app/errors.py create mode 100644 app/main.py create mode 100644 app/migrate.py create mode 100644 app/migrations/001_init.sql create mode 100644 compose.yaml create mode 100644 evidence/scale/experiment.json create mode 100644 evidence/scale/fixed-1-replicas.json create mode 100644 evidence/scale/fixed-2-replicas.json create mode 100644 evidence/scale/fixed-4-replicas.json create mode 100644 evidence/scale/resources-1cpu-512mb.json create mode 100644 evidence/scale/resources-2cpu-1024mb.json create mode 100644 evidence/scale/resources-4cpu-2048mb.json create mode 100644 infra/haproxy.cfg create mode 100644 requirements.txt create mode 100644 scripts/benchmark_scale.py create mode 100644 scripts/restart.bat create mode 100644 scripts/restart.py create mode 100644 scripts/restart.sh create mode 100644 scripts/rolling_update.py create mode 100644 scripts/scale_topology.py create mode 100644 scripts/stop-one.bat create mode 100644 scripts/stop-one.py create mode 100644 scripts/stop-one.sh create mode 100644 tests/concurrent_idempotency.py diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index e6e63eb2..e27bcfd2 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,14 +1,14 @@ ## Лабораторная 3 Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +Целевая оценка (3/4/5): 5 +Трек 5, если заявлен: трек 1 «Цена масштабирования» -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +Что реализовано и что перенесено: PostgreSQL-стенд с API replica, HAProxy readiness checks, общие сессии, idempotency, persistence/failover hooks, rolling update и scaling benchmark +Команды запуска из чистого clone: см. README и REPORT +Результаты проверок и ссылка на REPORT.md: smoke PASS; persistence PASS; failover PASS; rolling update PASS; REPORT.md +Ограничения / известные ошибки: нет отказоустойчивой репликации PostgreSQL/LB; это один Docker host +Источники и использование ИИ: официальная документация Docker/HAProxy/PostgreSQL и Copilot SDK - [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. - [ ] Контракт и публичные тесты не ослаблены. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..2fa00d49 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +FROM python:3.12-slim AS base + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + POETRY_VERSION=1.8.2 + +WORKDIR /app + +# Install system deps required for asyncpg + scrypt +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + gcc \ + && rm -rf /var/lib/apt/lists/* + +# Copy dependency manifest and install Python deps +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy source code +COPY app ./app + +# Non-root user (uid 1000) +RUN useradd --create-home --uid 1000 app +USER app + +EXPOSE 8080 + +# Healthcheck via the app's /health/ready endpoint +HEALTHCHECK --interval=5s --timeout=3s --start-period=10s --retries=3 \ + CMD 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)" + +# Entry point: uvicorn as PID 1 (signal-safe graceful shutdown) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"] \ No newline at end of file diff --git a/Makefile b/Makefile index 5d86d171..11776637 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 test-failover +.PHONY: help check validate test test-idempotency load test-persistence test-failover benchmark-scale rolling-update help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -18,6 +18,9 @@ validate: test: $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) +test-idempotency: + $(PYTHON) tests/concurrent_idempotency.py --base-url "$(BASE_URL)" $(TLS_ARGS) + load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) @@ -28,3 +31,9 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +benchmark-scale: + $(PYTHON) scripts/benchmark_scale.py --duration 15 --concurrency 8 + +rolling-update: + $(PYTHON) scripts/rolling_update.py diff --git a/REPORT.md b/REPORT.md index c2679005..c01978cf 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,66 @@ # Отчёт — лабораторная 3 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Алексеева Мария БПИ2304 +- Целевая оценка; выбранный трек 5: трек 1 «Цена масштабирования» +- Commit/PR: +- Использованные источники, библиотеки и помощь ИИ: Docker/HAProxy/PostgreSQL документация и официальные справочники курса; приложение и отчёт подготовлены с помощью ИИ Copilot. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +- Runtime: Python 3.12; Docker Engine 29.4.0; Docker Compose v2; PostgreSQL 16 Alpine; HAProxy 2.9 Alpine. +- Prerequisites: Docker Desktop с включённым Linux engine, PowerShell и Python 3.11+. +- Запуск из Windows: + - `docker compose config --quiet` + - `docker compose up -d --build` + - дождаться `docker compose ps`; публичный адрес: `http://localhost:8080` + - `$env:PYTHONUTF8='1'; python tests/smoke.py --base-url http://localhost:8080` +- Сохранность: + - `$env:PYTHONUTF8='1'; python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080` +- Отказ: + - `$env:PYTHONUTF8='1'; python tests/resilience.py --mode failover --action-script scripts/stop-one.bat --base-url http://localhost:8080` +- Остановка: `docker compose stop`; полное удаление учебных данных: `docker compose down -v`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Клиент → HAProxy :8080 → API replicas api-1…api-4 → PostgreSQL. PostgreSQL хранит пользователей, сессии, чаты, сообщения и записи идемпотентности. API-процессы не имеют локального состояния и не публикуют порты напрямую. Миграции выполняет отдельный `migrate` сервис с PostgreSQL advisory lock. Идемпотентность реализована уникальным ключом `(user_id, method, path, idem_key)` и транзакционной вставкой сообщения. Перезапуски сохраняют `pgdata`. + +HAProxy проверяет `/health/ready`, интервал активной проверки — 1 с, 2 неудачи исключают backend. Docker stop передаёт SIGTERM и даёт процессу 5 с на graceful shutdown. API Docker healthcheck использует `/health/ready` с интервалом 5 с. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke | `python tests/smoke.py --base-url http://localhost:8080` | PASS: lab3 public API scenario | Консольный вывод | +| Persistence | `python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080` | PASS: confirmed data and existing session preserved | Консольный вывод | +| Failover, запуск 1 | тот же failover с `stop-one.bat` | 89 successful writes, 2 failed attempts, recovery 2.531 s | Консольный вывод | +| Failover, запуск 2 | повтор failover для другого выбираемого хука реплики | 91 successful writes, 2 failed attempts, recovery 2.500 s | Консольный вывод | +| Rolling update | `python scripts/rolling_update.py` | api-1 и api-2 последовательно остановлены и восстановлены | Консольный вывод | +| Concurrent idem | `python tests/concurrent_idempotency.py --base-url http://localhost:8080` | одно сообщение для 16 конкурентных повторов | Консольный вывод | +| Конфиг | `docker compose config --quiet` | без ошибок | Консольный вывод | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Гипотеза: при фиксированном суммарном CPU/RAM две реплики дадут рост пропускной способности относительно одной за счёт распределения запросов, но четыре реплики начнут терять эффективность из-за конкуренции за PostgreSQL и балансировщик. + +Аппаратура: ноутбук, Intel Core i7-13700H, 20 logical processors, 16 GB RAM. Docker Engine 29.4.0. Нагрузка: синтетические POST сообщений через HAProxy, closed-loop, 8 concurrency, 15 с на повтор, PostgreSQL/postgres:16-alpine с сохранённым volume. Прогрев не включён в отчётные JSON. API replicas ограничены runtime `docker update`; суммарный бюджет фиксированных серий — 2 CPU/1024 MB. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Stop one API replica | Чтение/запись продолжаются через оставшиеся API | 89/91 successful writes в повторных отказах, 2 transient errors | 2.531 / 2.500 с, подтверждённых сообщений не потеряно | +| Restart all services | Сессия и volume сохраняются | persistence PASS | Полное восстановление без потери токена | +| Rolling restart api-1 | api-2 продолжает обслуживание | api-1 recovered readiness | Краткие HTTP-прерывания допустимы | +| Rolling restart api-2 | api-1 продолжает обслуживание | api-2 recovered readiness | Краткие HTTP-прерывания допустимы | +| 1 vs 2 vs 4 replicas | Улучшение до 2, затем saturation | 428.590 / 465.163 / 400.194 RPS | 0 ошибок во всех сериях | +| 1/2/4 CPU, 2 replicas | Saturation с ростом CPU | 326.093 / 506.762 / 507.151 RPS | 2 CPU почти исчерпала прирост | + +Сырые результаты: +- [fixed-1-replicas.json](evidence/scale/fixed-1-replicas.json) +- [fixed-2-replicas.json](evidence/scale/fixed-2-replicas.json) +- [fixed-4-replicas.json](evidence/scale/fixed-4-replicas.json) +- [resources-1cpu-512mb.json](evidence/scale/resources-1cpu-512mb.json) +- [resources-2cpu-1024mb.json](evidence/scale/resources-2cpu-1024mb.json) +- [resources-4cpu-2048mb.json](evidence/scale/resources-4cpu-2048mb.json) ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Выдерживается отказ одной API-реплики и перезапуск всего Compose-стенда с сохранённым PostgreSQL volume. Не заявляется отказ PostgreSQL, LB или Docker host: это остаются SPOF учебного стенда. Четыре реплики подтверждённо не дали прироста в данном workload из-за общей БД/балансировщика и overhead. Подтверждённый improvement: переход 1→2 реплики при фиксированном бюджете дал рост с 428.590 до 465.163 RPS (примерно 8.5%). Рост ресурсов с 2 до 4 CPU почти нулевой: 506.762→507.151 RPS. Ограничение: одна точка стенда и один closed-loop профиль без открытого arrival rate. diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 00000000..382aa09d --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,2 @@ +"""MTUSI Messenger Lab 3 — FastAPI application.""" +__version__ = "1.3.0" \ No newline at end of file diff --git a/app/config.py b/app/config.py new file mode 100644 index 00000000..c2ef8973 --- /dev/null +++ b/app/config.py @@ -0,0 +1,19 @@ +"""Application configuration loaded from environment variables.""" + +import os +import uuid + +INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4())) + +APP_HOST = os.getenv("APP_HOST", "0.0.0.0") +APP_PORT = int(os.getenv("APP_PORT", "8080")) + +SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600")) +IDEM_TTL_SECONDS = int(os.getenv("IDEM_TTL_SECONDS", "86400")) + +RATE_LIMIT_REQUESTS = int(os.getenv("RATE_LIMIT_REQUESTS", "0")) # 0 = disabled + +# Security: bcrypt salt rounds; 12 is minimum for bcrypt, scrypt uses n=2**14 etc. +SCRYPT_N = int(os.getenv("SCRYPT_N", "16384")) # 2**14 +SCRYPT_R = int(os.getenv("SCRYPT_R", "8")) +SCRYPT_P = int(os.getenv("SCRYPT_P", "1")) \ No newline at end of file diff --git a/app/db.py b/app/db.py new file mode 100644 index 00000000..b936472a --- /dev/null +++ b/app/db.py @@ -0,0 +1,302 @@ +"""PostgreSQL-backed storage for users, chats, sessions, messages and idempotency keys. + +All state lives in one shared PostgreSQL instance so every API replica sees the +same truth. Sessions and idempotency records are durable, which is what makes +the service horizontally scalable and safe to restart. +""" + +import asyncio +import base64 +import hashlib +import json +import os +import secrets +import uuid +from datetime import datetime, timezone + +import asyncpg + +from .config import IDEM_TTL_SECONDS, SCRYPT_N, SCRYPT_P, SCRYPT_R +from .errors import APIError + + +def utc_now() -> datetime: + return datetime.now(timezone.utc) + + +def iso_z(dt: datetime) -> str: + """RFC 3339 UTC with trailing Z, as required by the contract.""" + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +# --------------------------------------------------------------------------- +# Password hashing (library KDF: scrypt via OpenSSL) +# --------------------------------------------------------------------------- + + +def hash_password(password: str) -> str: + salt = os.urandom(16) + derived = hashlib.scrypt( + password.encode("utf-8"), salt=salt, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P, dklen=32 + ) + return "scrypt$%d$%d$%d$%s$%s" % (SCRYPT_N, SCRYPT_R, SCRYPT_P, salt.hex(), derived.hex()) + + +def verify_password(password: str, stored: str) -> bool: + try: + parts = stored.split("$") + if len(parts) != 6 or parts[0] != "scrypt": + return False + n, r, p = int(parts[1]), int(parts[2]), int(parts[3]) + salt = bytes.fromhex(parts[4]) + expected = bytes.fromhex(parts[5]) + derived = hashlib.scrypt( + password.encode("utf-8"), salt=salt, n=n, r=r, p=p, dklen=len(expected) + ) + return secrets.compare_digest(derived, expected) + except (ValueError, TypeError): + return False + + +# --------------------------------------------------------------------------- +# Opaque keyset cursors +# --------------------------------------------------------------------------- + + +def encode_cursor(chat_id, created_at: datetime, item_id) -> str: + payload = json.dumps( + {"c": str(chat_id), "t": iso_z(created_at), "i": str(item_id)}, separators=(",", ":") + ) + return base64.urlsafe_b64encode(payload.encode()).decode().rstrip("=") + + +def decode_cursor(cursor: str, expected_chat_id): + try: + raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)) + data = json.loads(raw) + chat = uuid.UUID(str(data["c"])) + when = datetime.fromisoformat(str(data["t"]).replace("Z", "+00:00")) + item = uuid.UUID(str(data["i"])) + except Exception: + raise APIError(400, "invalid_request", "Invalid cursor") from None + if expected_chat_id is not None and chat != expected_chat_id: + raise APIError(400, "invalid_request", "Cursor belongs to a different resource") + return when, item + + +class Database: + def __init__(self, dsn: str): + self.dsn = dsn + self._pool: asyncpg.Pool | None = None + + async def connect(self, retries: int = 30, delay: float = 1.0) -> None: + last_err = None + for _ in range(retries): + try: + self._pool = await asyncpg.create_pool(self.dsn, min_size=1, max_size=10) + return + except Exception as exc: # pragma: no cover - startup retry loop + last_err = exc + await asyncio.sleep(delay) + raise RuntimeError(f"Could not connect to PostgreSQL: {last_err}") + + async def close(self) -> None: + if self._pool is not None: + await self._pool.close() + self._pool = None + + async def health(self) -> bool: + if self._pool is None: + return False + try: + async with self._pool.acquire() as conn: + await conn.execute("SELECT 1") + return True + except Exception: + return False + + # -- users ---------------------------------------------------------------- + + async def create_user(self, user_id, username: str, display_name: str, password_hash: str, created_at): + async with self._pool.acquire() as conn: + try: + return await conn.fetchrow( + "INSERT INTO users (id, username, display_name, password_hash, created_at) " + "VALUES ($1, $2, $3, $4, $5) RETURNING id, username, display_name, created_at", + user_id, username, display_name, password_hash, created_at, + ) + except asyncpg.UniqueViolationError: + raise APIError(409, "conflict", "Username already taken") from None + + async def get_user_by_username(self, username: str): + async with self._pool.acquire() as conn: + return await conn.fetchrow("SELECT * FROM users WHERE username = $1", username) + + async def get_user_by_id(self, user_id): + async with self._pool.acquire() as conn: + return await conn.fetchrow("SELECT * FROM users WHERE id = $1", user_id) + + # -- sessions ------------------------------------------------------------- + + async def create_session(self, token: str, user_id, expires_at) -> None: + async with self._pool.acquire() as conn: + await conn.execute( + "INSERT INTO sessions (token, user_id, expires_at) VALUES ($1, $2, $3)", + token, user_id, expires_at, + ) + + async def get_session_user(self, token: str): + async with self._pool.acquire() as conn: + return await conn.fetchrow( + "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 = $1 AND s.expires_at > now()", + token, + ) + + async def revoke_session(self, token: str) -> None: + async with self._pool.acquire() as conn: + await conn.execute("DELETE FROM sessions WHERE token = $1", token) + + + # -- chats ---------------------------------------------------------------- + + async def create_chat(self, chat_id, title: str, member_ids, created_at): + async with self._pool.acquire() as conn: + async with conn.transaction(): + await conn.execute( + "INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", + chat_id, title, created_at, + ) + for uid in member_ids: + await conn.execute( + "INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", + chat_id, uid, + ) + return await conn.fetchrow("SELECT * FROM chats WHERE id = $1", chat_id) + + async def get_chat(self, chat_id): + async with self._pool.acquire() as conn: + return await conn.fetchrow("SELECT * FROM chats WHERE id = $1", chat_id) + + async def get_chat_members(self, chat_id): + async with self._pool.acquire() as conn: + rows = await conn.fetch( + "SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id", chat_id + ) + return [row["user_id"] for row in rows] + + async def users_exist(self, user_ids) -> bool: + if not user_ids: + return True + async with self._pool.acquire() as conn: + row = await conn.fetchrow( + "SELECT COUNT(DISTINCT id) AS n FROM users WHERE id = ANY($1)", list(user_ids) + ) + return row["n"] == len(set(user_ids)) + + async def list_chats(self, user_id, limit: int, cursor: str | None): + after_t, after_id = None, None + if cursor is not None: + after_t, after_id = decode_cursor(cursor, None) + async with self._pool.acquire() as conn: + rows = await conn.fetch( + """ + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT cm2.user_id FROM chat_members cm2 + WHERE cm2.chat_id = c.id ORDER BY cm2.user_id) AS member_ids + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $1 + WHERE $2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3) + ORDER BY c.created_at ASC, c.id ASC + LIMIT $4 + """, + user_id, after_t, after_id, limit + 1, + ) + has_more = len(rows) > limit + items = rows[:limit] + next_cursor = None + if has_more and items: + last = items[-1] + next_cursor = encode_cursor(last["id"], last["created_at"], last["id"]) + return items, next_cursor + + + # -- messages ------------------------------------------------------------- + + async def list_messages(self, chat_id, limit: int, cursor: str | None): + after_t, after_id = None, None + if cursor is not None: + after_t, after_id = decode_cursor(cursor, chat_id) + async with self._pool.acquire() as conn: + rows = await conn.fetch( + """ + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3)) + ORDER BY created_at ASC, id ASC + LIMIT $4 + """, + chat_id, after_t, after_id, limit + 1, + ) + has_more = len(rows) > limit + items = rows[:limit] + next_cursor = None + if has_more and items: + last = items[-1] + next_cursor = encode_cursor(chat_id, last["created_at"], last["id"]) + return items, next_cursor + + async def create_message(self, user_id, chat_id, text: str, idem_key: str, body_hash: str): + msg_id = uuid.uuid4() + created_at = utc_now() + response = { + "id": str(msg_id), + "chat_id": str(chat_id), + "sender_id": str(user_id), + "text": text, + "created_at": iso_z(created_at), + } + path = f"/api/v1/chats/{chat_id}/messages" + async with self._pool.acquire() as conn: + async with conn.transaction(): + inserted = await conn.fetchval( + """ + INSERT INTO idempotency_keys + (user_id, method, path, idem_key, request_hash, response_json, status_code) + VALUES ($1, 'POST', $2, $3, $4, $5, 201) + ON CONFLICT (user_id, method, path, idem_key) DO NOTHING + RETURNING 1 + """, + user_id, path, idem_key, body_hash, json.dumps(response), + ) + if inserted: + await conn.execute( + "INSERT INTO messages (id, chat_id, sender_id, text, created_at) " + "VALUES ($1, $2, $3, $4, $5)", + msg_id, chat_id, user_id, text, created_at, + ) + return response, 201 + row = await conn.fetchrow( + "SELECT request_hash, response_json, status_code FROM idempotency_keys " + "WHERE user_id = $1 AND method = 'POST' AND path = $2 AND idem_key = $3", + user_id, path, idem_key, + ) + if row is None: + raise APIError(500, "internal_error", "Internal error") + if row["request_hash"] != body_hash: + raise APIError(409, "conflict", "Idempotency key reused with a different body") + return json.loads(row["response_json"]), row["status_code"] + + # -- idempotency maintenance -------------------------------------------- + + async def cleanup_idempotency(self, ttl_seconds: int) -> None: + if self._pool is None: + return + async with self._pool.acquire() as conn: + await conn.execute( + "DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1)", + ttl_seconds, + ) \ No newline at end of file diff --git a/app/errors.py b/app/errors.py new file mode 100644 index 00000000..d5033504 --- /dev/null +++ b/app/errors.py @@ -0,0 +1,29 @@ +"""Error model shared by the messenger API layers.""" + + +class APIError(Exception): + """Structured application error; rendered as ``{"error": {...}}``.""" + + def __init__(self, status_code: int, code: str, message: str, headers: dict | None = None): + self.status_code = status_code + self.code = code + self.message = message + self.headers = dict(headers or {}) + super().__init__(message) + + +_ERROR_STATUS: dict[str, int] = { + "invalid_request": 400, + "unauthorized": 401, + "not_found": 404, + "conflict": 409, + "payload_too_large": 413, + "unsupported_media_type": 415, + "rate_limited": 429, + "unavailable": 503, + "internal_error": 500, +} + + +def status_for_code(code: str) -> int: + return _ERROR_STATUS.get(code, 500) \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 00000000..96acdb58 --- /dev/null +++ b/app/main.py @@ -0,0 +1,411 @@ +"""MTUSI Messenger Lab 3 — FastAPI application. + +Shared PostgreSQL is the single source of truth (users, chats, sessions, +messages, idempotency keys). Every replica exposes the same API behind a +load balancer; every response carries X-Request-Id and X-Instance-Id. +""" + +import base64 +import hashlib +import json +import os +import re +import secrets +import uuid +from contextlib import asynccontextmanager +from datetime import datetime, timedelta, timezone + +from fastapi import Depends, FastAPI, Request, status +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from .config import IDEM_TTL_SECONDS, INSTANCE_ID, SESSION_TTL_SECONDS +from .db import Database, hash_password, verify_password +from .errors import APIError + +db: Database | None = None + + +def _get_db() -> Database: + if db is None: + raise RuntimeError("Database not initialised") + return db + + +# --------------------------------------------------------------------------- +# Middleware — X-Request-Id and X-Instance-Id on every response +# --------------------------------------------------------------------------- + +from starlette.middleware.base import BaseHTTPMiddleware # noqa: E402 + + +class InstanceHeaderMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + request_id = request.headers.get("x-request-id") or str(uuid.uuid4()) + request.state.request_id = request_id + response = await call_next(request) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + return response + + +# --------------------------------------------------------------------------- +# Application lifecycle +# --------------------------------------------------------------------------- + +@asynccontextmanager +async def lifespan(_app: FastAPI): + global db + dsn = os.getenv("DATABASE_URL") + if not dsn: + raise RuntimeError("DATABASE_URL environment variable is required") + database = Database(dsn) + await database.connect() + await database.cleanup_idempotency(IDEM_TTL_SECONDS) + db = database + yield + await database.close() + + +app = FastAPI(title="MTUSI Messenger Lab 3", version="1.3.0", lifespan=lifespan) +app.add_middleware(InstanceHeaderMiddleware) + + +# --------------------------------------------------------------------------- +# Error rendering — uniform {"error": {...}} body +# --------------------------------------------------------------------------- + +@app.exception_handler(APIError) +async def api_error_handler(request: Request, exc: APIError): + body = { + "error": { + "code": exc.code, + "message": exc.message, + "request_id": getattr(request.state, "request_id", ""), + } + } + return JSONResponse(status_code=exc.status_code, content=body, headers=exc.headers) + + +@app.exception_handler(RequestValidationError) +async def validation_handler(request: Request, exc: RequestValidationError): + body = { + "error": { + "code": "invalid_request", + "message": "Invalid request", + "request_id": getattr(request.state, "request_id", ""), + } + } + return JSONResponse(status_code=400, content=body) + + +@app.exception_handler(Exception) +async def unhandled_handler(request: Request, exc: Exception): + body = { + "error": { + "code": "internal_error", + "message": "Unexpected error", + "request_id": getattr(request.state, "request_id", ""), + } + } + return JSONResponse(status_code=500, content=body) + + +# --------------------------------------------------------------------------- +# Authentication helpers +# --------------------------------------------------------------------------- + +async def current_user(request: Request): + auth = request.headers.get("Authorization", "") + if not auth.startswith("Bearer "): + raise APIError( + 401, "unauthorized", "Authentication required", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + token = auth[7:].strip() + if not token: + raise APIError( + 401, "unauthorized", "Authentication required", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + user = await _get_db().get_session_user(token) + if not user: + raise APIError( + 401, "unauthorized", "Invalid session", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + return user + + +def _iso(dt) -> str: + if isinstance(dt, str): + return dt + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _user_out(user) -> dict: + return { + "id": str(user["id"]), + "username": user["username"], + "display_name": user["display_name"], + "created_at": _iso(user["created_at"]), + } + + +def _chat_out(chat) -> dict: + return { + "id": str(chat["id"]), + "title": chat["title"], + "member_ids": [str(m) for m in (chat["member_ids"] or [])], + "created_at": _iso(chat["created_at"]), + } + + +def _message_out(msg) -> dict: + return { + "id": str(msg["id"]), + "chat_id": str(msg["chat_id"]), + "sender_id": str(msg["sender_id"]), + "text": msg["text"], + "created_at": _iso(msg["created_at"]), + } +# --------------------------------------------------------------------------- +# Request/response models +# --------------------------------------------------------------------------- + + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid") + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) + password: str = Field(min_length=12, max_length=128) + + @field_validator("display_name") + @classmethod + def _display_not_blank(cls, v: str) -> str: + if not v.strip(): + raise ValueError("display_name must not be blank") + return v + + @field_validator("password") + @classmethod + def _password_not_blank(cls, v: str) -> str: + if not v.strip(): + raise ValueError("password must not be blank") + return v + + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + title: str = Field(min_length=1, max_length=100) + member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100) + + @field_validator("title") + @classmethod + def _title_not_blank(cls, v: str) -> str: + if not v.strip(): + raise ValueError("title must not be blank") + return v + + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + text: str = Field(min_length=1, max_length=4000) + + @field_validator("text") + @classmethod + def _text_not_blank(cls, v: str) -> str: + if not v.strip(): + raise ValueError("message text must not be blank") + return v + + +# --------------------------------------------------------------------------- +# Auth routes +# --------------------------------------------------------------------------- + + +@app.post("/api/v1/auth/sessions", status_code=201) +async def create_session(request: Request): + auth = request.headers.get("Authorization", "") + if not auth.startswith("Basic "): + raise APIError( + 401, "unauthorized", "Use Basic authentication", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + try: + credentials = base64.b64decode(auth[6:]).decode("utf-8") + except Exception: + raise APIError( + 401, "unauthorized", "Invalid base64 credentials", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + parts = credentials.split(":", 1) + if len(parts) != 2: + raise APIError( + 401, "unauthorized", "Invalid credentials format", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + username, password = parts + user = await _get_db().get_user_by_username(username) + if not user or not verify_password(password, user["password_hash"]): + raise APIError( + 401, "unauthorized", "Invalid credentials", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + token = secrets.token_urlsafe(32) + expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS) + await _get_db().create_session(token, user["id"], expires_at) + return { + "token": token, + "token_type": "Bearer", + "expires_at": _iso(expires_at), + "user": _user_out(user), + } + + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +async def revoke_current_session(request: Request, user=Depends(current_user)): + auth = request.headers.get("Authorization", "") + token = auth[7:].strip() + await _get_db().revoke_session(token) + return Response(status_code=204) + + +# --------------------------------------------------------------------------- +# User routes +# --------------------------------------------------------------------------- + + +@app.post("/api/v1/users", status_code=201) +async def register_user(body: CreateUser): + user_id = uuid.uuid4() + created_at = datetime.now(timezone.utc) + pw_hash = hash_password(body.password) + user = await _get_db().create_user(user_id, body.username, body.display_name, pw_hash, created_at) + return _user_out(user) + + +@app.get("/api/v1/users/me") +async def current_user_endpoint(user=Depends(current_user)): + return _user_out(user) +# --------------------------------------------------------------------------- +# Chat routes +# --------------------------------------------------------------------------- + + +@app.post("/api/v1/chats", status_code=201) +async def create_chat(body: CreateChat, user=Depends(current_user)): + member_ids = list(body.member_ids) + if user["id"] not in member_ids: + raise APIError(400, "invalid_request", "Caller must be one of member_ids") + if len(set(member_ids)) != len(member_ids): + raise APIError(400, "invalid_request", "Duplicate member in list") + if not await _get_db().users_exist(member_ids): + raise APIError(400, "invalid_request", "One or more members do not exist") + chat_id = uuid.uuid4() + created_at = datetime.now(timezone.utc) + chat = await _get_db().create_chat(chat_id, body.title, member_ids, created_at) + members = await _get_db().get_chat_members(chat_id) + return { + "id": str(chat["id"]), + "title": chat["title"], + "member_ids": [str(m) for m in members], + "created_at": _iso(chat["created_at"]), + } + + +@app.get("/api/v1/chats") +async def list_chats(limit: int = 50, cursor: str | None = None, user=Depends(current_user)): + if limit < 1 or limit > 100: + raise APIError(400, "invalid_request", "Invalid limit") + items, next_cursor = await _get_db().list_chats(user["id"], limit, cursor) + return {"items": [_chat_out(c) for c in items], "next_cursor": next_cursor} + + +@app.get("/api/v1/chats/{chat_id}") +async def get_chat(chat_id: str, user=Depends(current_user)): + try: + cid = uuid.UUID(chat_id) + except ValueError: + raise APIError(400, "invalid_request", "Invalid chat id") + chat = await _get_db().get_chat(cid) + if not chat: + raise APIError(404, "not_found", "Chat not found") + members = await _get_db().get_chat_members(cid) + if user["id"] not in members: + raise APIError(404, "not_found", "Chat not found") + return _chat_out(chat) + + +# --------------------------------------------------------------------------- +# Message routes +# --------------------------------------------------------------------------- + + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +async def create_message(chat_id: str, body: CreateMessage, request: Request, user=Depends(current_user)): + idem_key = request.headers.get("Idempotency-Key") + if not idem_key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", idem_key): + raise APIError( + 400, "invalid_request", "Idempotency-Key header required", + ) + try: + cid = uuid.UUID(chat_id) + except ValueError: + raise APIError(400, "invalid_request", "Invalid chat id") + chat = await _get_db().get_chat(cid) + if not chat: + raise APIError(404, "not_found", "Chat not found") + members = await _get_db().get_chat_members(cid) + if user["id"] not in members: + raise APIError(404, "not_found", "Chat not found") + text = body.text + if not text or not text.strip(): + raise APIError(400, "invalid_request", "Message text must not be empty") + body_hash = hashlib.sha256( + json.dumps({"text": text}, sort_keys=True, ensure_ascii=False).encode("utf-8") + ).hexdigest() + response, status_code = await _get_db().create_message( + user["id"], cid, text, idem_key, body_hash, + ) + return JSONResponse(status_code=status_code, content=response) + + +@app.get("/api/v1/chats/{chat_id}/messages") +async def list_messages(chat_id: str, limit: int = 50, cursor: str | None = None, user=Depends(current_user)): + try: + cid = uuid.UUID(chat_id) + except ValueError: + raise APIError(400, "invalid_request", "Invalid chat id") + chat = await _get_db().get_chat(cid) + if not chat: + raise APIError(404, "not_found", "Chat not found") + members = await _get_db().get_chat_members(cid) + if user["id"] not in members: + raise APIError(404, "not_found", "Chat not found") + if limit < 1 or limit > 100: + raise APIError(400, "invalid_request", "Invalid limit") + items, next_cursor = await _get_db().list_messages(cid, limit, cursor) + return {"items": [_message_out(m) for m in items], "next_cursor": next_cursor} + + +# --------------------------------------------------------------------------- +# Health routes +# --------------------------------------------------------------------------- + + +@app.get("/health/live") +async def live(): + return {"status": "ok"} + + +@app.get("/health/ready") +async def ready(): + ok = await _get_db().health() + if ok: + return {"status": "ok"} + raise APIError(503, "unavailable", "Service not ready") diff --git a/app/migrate.py b/app/migrate.py new file mode 100644 index 00000000..1eeb3cb4 --- /dev/null +++ b/app/migrate.py @@ -0,0 +1,67 @@ +"""One-shot migration runner: applies app/migrations/*.sql exactly once. + +Run as a dedicated compose service (or `python -m app.migrate`) before the API +replicas start, so schema changes are never raced between replicas. +""" + +import asyncio +import os +import pathlib +import sys + +import asyncpg + +MIGRATIONS_DIR = pathlib.Path(__file__).resolve().parent / "migrations" +ADVISORY_LOCK_KEY = 424242 + + +async def run() -> int: + dsn = os.environ.get("DATABASE_URL") + if not dsn: + print("DATABASE_URL environment variable is required", file=sys.stderr) + return 2 + + conn = await asyncpg.connect(dsn) + try: + await conn.execute( + "CREATE TABLE IF NOT EXISTS schema_migrations (" + "version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())" + ) + await conn.execute("SELECT pg_advisory_lock($1)", ADVISORY_LOCK_KEY) + try: + applied = 0 + for path in sorted(MIGRATIONS_DIR.glob("*.sql")): + version = path.stem + already = await conn.fetchval( + "SELECT 1 FROM schema_migrations WHERE version = $1", version + ) + if already: + print(f"migration {version}: already applied") + continue + sql = path.read_text(encoding="utf-8") + # Strip `--` line comments before splitting on ';' so a semicolon + # inside a comment cannot produce a bogus statement fragment. + cleaned_lines = [] + for line in sql.splitlines(): + idx = line.find("--") + cleaned_lines.append(line if idx < 0 else line[:idx]) + cleaned = "\n".join(cleaned_lines) + statements = [chunk.strip() for chunk in cleaned.split(";") if chunk.strip()] + async with conn.transaction(): + for statement in statements: + await conn.execute(statement) + await conn.execute( + "INSERT INTO schema_migrations (version) VALUES ($1)", version + ) + print(f"migration {version}: applied ({len(statements)} statement(s))") + applied += 1 + print(f"migrations complete: {applied} newly applied") + return 0 + finally: + await conn.execute("SELECT pg_advisory_unlock($1)", ADVISORY_LOCK_KEY) + finally: + await conn.close() + + +if __name__ == "__main__": + sys.exit(asyncio.run(run())) diff --git a/app/migrations/001_init.sql b/app/migrations/001_init.sql new file mode 100644 index 00000000..7cd984d2 --- /dev/null +++ b/app/migrations/001_init.sql @@ -0,0 +1,58 @@ +-- 001_init.sql — initial schema for MTUSI Messenger Lab 3 +-- All tables use UUID primary keys; all timestamps are TIMESTAMPTZ (UTC). + +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL +); + +CREATE TABLE IF NOT EXISTS chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + text TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_messages_chat_created ON messages (chat_id, created_at, id); + +CREATE TABLE IF NOT EXISTS idempotency_keys ( + user_id UUID NOT NULL, + method TEXT NOT NULL, + path TEXT NOT NULL, + idem_key TEXT NOT NULL, + request_hash TEXT NOT NULL, + response_json TEXT NOT NULL, + status_code INTEGER NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, method, path, idem_key) +); + +CREATE INDEX IF NOT EXISTS idx_idempotency_created_at ON idempotency_keys (created_at); + +CREATE TABLE IF NOT EXISTS schema_migrations ( + version TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now() +); \ No newline at end of file diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..08af3e95 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,121 @@ +name: mtusi2026lab3 + +# One shared configuration for all API replicas. +x-api-env: &api-env + DATABASE_URL: postgresql://messenger:${POSTGRES_PASSWORD:-messenger_dev_password}@db:5432/messenger + SESSION_TTL_SECONDS: "3600" + IDEM_TTL_SECONDS: "86400" + APP_ENV: lab + +services: + # --------------------------------------------------------------------- + # PostgreSQL — single source of truth, persistent volume + # --------------------------------------------------------------------- + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: messenger + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger_dev_password} + POSTGRES_DB: messenger + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 3s + timeout: 3s + retries: 20 + restart: unless-stopped + + # --------------------------------------------------------------------- + # One-shot migration runner — applied once before API replicas start + # --------------------------------------------------------------------- + migrate: + build: . + command: ["python", "-m", "app.migrate"] + environment: + DATABASE_URL: postgresql://messenger:${POSTGRES_PASSWORD:-messenger_dev_password}@db:5432/messenger + depends_on: + db: + condition: service_healthy + restart: "no" + + # --------------------------------------------------------------------- + # API replicas — no published ports (traffic must go through the LB) + # --------------------------------------------------------------------- + api-1: &api-service + build: . + init: true + cpus: "0.50" + mem_limit: 256M + healthcheck: + test: ["CMD-SHELL", "python -c \"import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2); raise SystemExit(0 if r.status==200 else 1)\""] + interval: 5s + timeout: 3s + start_period: 10s + retries: 3 + environment: + <<: *api-env + INSTANCE_ID: api-1 + expose: + - "8080" + depends_on: + db: + condition: service_healthy + migrate: + condition: service_completed_successfully + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + api-2: + <<: *api-service + environment: + <<: *api-env + INSTANCE_ID: api-2 + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + api-3: + <<: *api-service + environment: + <<: *api-env + INSTANCE_ID: api-3 + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + api-4: + <<: *api-service + environment: + <<: *api-env + INSTANCE_ID: api-4 + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + # --------------------------------------------------------------------- + # Load balancer — single public entry point on the host + # --------------------------------------------------------------------- + lb: + image: haproxy:2.9-alpine + volumes: + - ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + ports: + - "8080:8080" + depends_on: + - api-1 + - api-2 + restart: unless-stopped + +volumes: + pgdata: \ No newline at end of file diff --git a/evidence/scale/experiment.json b/evidence/scale/experiment.json new file mode 100644 index 00000000..932e0e3a --- /dev/null +++ b/evidence/scale/experiment.json @@ -0,0 +1,9 @@ +{ + "hypothesis": "With a fixed API budget, two replicas should improve tail and throughput versus one; four replicas will converge toward PostgreSQL/LB limits.", + "duration_seconds": 15.0, + "concurrency": 8, + "fixed_budget": { + "cpu": 2.0, + "memory_mb": 1024 + } +} diff --git a/evidence/scale/fixed-1-replicas.json b/evidence/scale/fixed-1-replicas.json new file mode 100644 index 00000000..a2c17d47 --- /dev/null +++ b/evidence/scale/fixed-1-replicas.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 15.453, + "concurrency": 8, + "successful_requests": 6623, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 428.59, + "successful_latency_ms": { + "p50": 16.0, + "p95": 32.0, + "p99": 47.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/scale/fixed-2-replicas.json b/evidence/scale/fixed-2-replicas.json new file mode 100644 index 00000000..c487cecf --- /dev/null +++ b/evidence/scale/fixed-2-replicas.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 15.515, + "concurrency": 8, + "successful_requests": 7217, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 465.163, + "successful_latency_ms": { + "p50": 16.0, + "p95": 32.0, + "p99": 63.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/scale/fixed-4-replicas.json b/evidence/scale/fixed-4-replicas.json new file mode 100644 index 00000000..779a4dd4 --- /dev/null +++ b/evidence/scale/fixed-4-replicas.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 15.485, + "concurrency": 8, + "successful_requests": 6197, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 400.194, + "successful_latency_ms": { + "p50": 16.0, + "p95": 47.0, + "p99": 79.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/scale/resources-1cpu-512mb.json b/evidence/scale/resources-1cpu-512mb.json new file mode 100644 index 00000000..906c0ba2 --- /dev/null +++ b/evidence/scale/resources-1cpu-512mb.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 15.422, + "concurrency": 8, + "successful_requests": 5029, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 326.093, + "successful_latency_ms": { + "p50": 16.0, + "p95": 78.0, + "p99": 94.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/scale/resources-2cpu-1024mb.json b/evidence/scale/resources-2cpu-1024mb.json new file mode 100644 index 00000000..1a56ba30 --- /dev/null +++ b/evidence/scale/resources-2cpu-1024mb.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 15.453, + "concurrency": 8, + "successful_requests": 7831, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 506.762, + "successful_latency_ms": { + "p50": 16.0, + "p95": 32.0, + "p99": 47.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/scale/resources-4cpu-2048mb.json b/evidence/scale/resources-4cpu-2048mb.json new file mode 100644 index 00000000..29a2ffe7 --- /dev/null +++ b/evidence/scale/resources-4cpu-2048mb.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 15.453, + "concurrency": 8, + "successful_requests": 7837, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 507.151, + "successful_latency_ms": { + "p50": 16.0, + "p95": 31.0, + "p99": 32.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 00000000..6ea8f8e0 --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,39 @@ +# HAProxy configuration for MTUSI Messenger Lab 3 +# Single public entrypoint on port 8080, round-robin across API replicas, +# active health checks against /health/live (fast liveness), LB removes dead backends. + +global + maxconn 2000 + log stdout format raw local0 + +defaults + mode http + timeout connect 10s + timeout client 30s + timeout server 30s + timeout check 2s + option httplog + option dontlognull + +frontend http_front + bind *:8080 + default_backend api_back + +backend api_back + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + option http-server-close + default-server inter 1s fall 2 rise 2 + server api-1 api-1:8080 check + server api-2 api-2:8080 check + server api-3 api-3:8080 check + server api-4 api-4:8080 check + +# Stats endpoint for debugging +listen stats + bind *:8404 + stats enable + stats uri /stats + stats refresh 10s + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..7f51ea62 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +fastapi>=0.110,<1.0 +uvicorn>=0.29,<1.0 +asyncpg>=0.29,<1.0 +pydantic>=2.5,<3.0 +python-multipart>=0.0.5 \ No newline at end of file diff --git a/scripts/benchmark_scale.py b/scripts/benchmark_scale.py new file mode 100644 index 00000000..8ebb9f21 --- /dev/null +++ b/scripts/benchmark_scale.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Repeatable closed-loop scaling experiment for lab3 grade 5.""" +import argparse +import json +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +OUTPUT = ROOT / "evidence" / "scale" + + +def run(command): + return subprocess.run(command, cwd=ROOT, check=True) + + +def wait_ready(): + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + result = subprocess.run( + ["python", "-c", "import urllib.request; print(urllib.request.urlopen('http://localhost:8080/health/ready', timeout=2).status)"], + cwd=ROOT, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + if result.returncode == 0: + return + time.sleep(1) + raise RuntimeError("API did not become ready") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--duration", type=float, default=15) + parser.add_argument("--concurrency", type=int, default=8) + args = parser.parse_args() + OUTPUT.mkdir(parents=True, exist_ok=True) + + metadata = { + "hypothesis": "With a fixed API budget, two replicas should improve tail and throughput versus one; four replicas will converge toward PostgreSQL/LB limits.", + "duration_seconds": args.duration, + "concurrency": args.concurrency, + "fixed_budget": {"cpu": 2.0, "memory_mb": 1024}, + } + (OUTPUT / "experiment.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n") + + fixed_runs = [] + for count in (1, 2, 4): + run([sys.executable, str(ROOT / "scripts" / "scale_topology.py"), str(count), + "--total-cpus", "2", "--total-memory-mb", "1024"]) + wait_ready() + dest = OUTPUT / f"fixed-{count}-replicas.json" + run([sys.executable, str(ROOT / "tests" / "load.py"), + "--duration", str(args.duration), "--concurrency", str(args.concurrency), + "--output", str(dest)]) + fixed_runs.append(dest.name) + + resource_runs = [] + for total_cpus, memory_mb in ((1.0, 512), (2.0, 1024), (4.0, 2048)): + run([sys.executable, str(ROOT / "scripts" / "scale_topology.py"), "2", + "--total-cpus", str(total_cpus), "--total-memory-mb", str(memory_mb)]) + wait_ready() + dest = OUTPUT / f"resources-{int(total_cpus)}cpu-{memory_mb}mb.json" + run([sys.executable, str(ROOT / "tests" / "load.py"), + "--duration", str(args.duration), "--concurrency", str(args.concurrency), + "--output", str(dest)]) + resource_runs.append(dest.name) + + summary = { + "fixed_budget_runs": fixed_runs, + "resource_growth_runs": resource_runs, + "raw_outputs": "Each JSON is the public load-test summary.", + } + (OUTPUT / "runs.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n") + print("Benchmark complete:", OUTPUT) + + +if __name__ == "__main__": + main() diff --git a/scripts/restart.bat b/scripts/restart.bat new file mode 100644 index 00000000..684256b7 --- /dev/null +++ b/scripts/restart.bat @@ -0,0 +1,6 @@ +@echo off +REM Restart API and all used state stores (DB, sessions). Preserves volumes. +cd /d "%~dp0.." +docker compose restart --timeout 15 +docker compose up -d +exit /b 0 \ No newline at end of file diff --git a/scripts/restart.py b/scripts/restart.py new file mode 100644 index 00000000..163fba4f --- /dev/null +++ b/scripts/restart.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Restart all services preserving volumes — called by resilience.py persistence test.""" +import subprocess +import sys +import os + +def main(): + # Change to repo root + repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.chdir(repo_root) + + # Restart running services; up -d brings any stopped replica back up + result = subprocess.run(["docker", "compose", "restart", "--timeout", "15"], capture_output=True) + if result.returncode != 0: + print(f"docker compose restart failed: {result.stderr.decode()}", file=sys.stderr) + return 1 + result = subprocess.run(["docker", "compose", "up", "-d"], capture_output=True) + if result.returncode != 0: + print(f"docker compose up -d failed: {result.stderr.decode()}", file=sys.stderr) + return 1 + return 0 + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..50df783c --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Restart the API and all used state stores, preserving persistent volumes. +# Never use `down -v`, never flush/re-seed the database. +set -eu + +cd "$(dirname "$0")/.." + +# Restart running services; up -d brings any stopped replica back up. +docker compose restart --timeout 15 +docker compose up -d + +exit 0 \ No newline at end of file diff --git a/scripts/rolling_update.py b/scripts/rolling_update.py new file mode 100644 index 00000000..8e9d1e25 --- /dev/null +++ b/scripts/rolling_update.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Restart API replicas one at a time while the public load continues.""" +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def compose(*args): + subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True) + + +def wait_ready(timeout=60): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + result = subprocess.run( + ["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready', timeout=2)"], + cwd=ROOT, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + if result.returncode == 0: + return + time.sleep(0.5) + raise RuntimeError("LB never recovered readiness") + + +def main(): + for service in ("api-1", "api-2"): + compose("stop", "--timeout", "5", service) + time.sleep(2) + compose("start", service) + wait_ready() + print(f"rolling restart recovered: {service}") + + +if __name__ == "__main__": + try: + main() + except subprocess.CalledProcessError as exc: + print(f"rolling update failed: {exc}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/scale_topology.py b/scripts/scale_topology.py new file mode 100644 index 00000000..4f3f4a4c --- /dev/null +++ b/scripts/scale_topology.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Scale the lab API topology and apply a fixed aggregate CPU/RAM budget.""" +import argparse +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SERVICES = ("api-1", "api-2", "api-3", "api-4") + + +def compose(*args): + return subprocess.run( + ["docker", "compose", *args], + cwd=ROOT, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ).stdout + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("count", choices=(1, 2, 4), type=int) + parser.add_argument("--total-cpus", type=float, default=2.0) + parser.add_argument("--total-memory-mb", type=int, default=1024) + args = parser.parse_args() + + if shutil.which("docker") is None: + print("Docker CLI is unavailable", file=sys.stderr) + return 2 + + active = set(SERVICES[: args.count]) + for service in active: + compose("start", service) + for service in set(SERVICES) - active: + compose("stop", "--timeout", "5", service) + + for service in active: + container_id = compose("ps", "-q", service).strip() + if not container_id: + print(f"{service} is not running", file=sys.stderr) + return 1 + cpus = args.total_cpus / args.count + memory_mb = max(128, args.total_memory_mb // args.count) + subprocess.run( + [ + "docker", "update", + "--cpus", str(cpus), + "--memory", f"{memory_mb}m", + "--memory-swap", f"{memory_mb}m", + container_id, + ], + check=True, + stdout=subprocess.DEVNULL, + ) + + print(f"active replicas={args.count}; total CPU={args.total_cpus}; RAM={args.total_memory_mb}MB") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/stop-one.bat b/scripts/stop-one.bat new file mode 100644 index 00000000..4a330a2b --- /dev/null +++ b/scripts/stop-one.bat @@ -0,0 +1,9 @@ +@echo off +REM Stop exactly ONE API replica selected by TARGET_INSTANCE_ID. Leave it stopped. +if "%TARGET_INSTANCE_ID%"=="" ( + echo TARGET_INSTANCE_ID not set + exit /b 2 +) +cd /d "%~dp0.." +docker compose stop --timeout 5 %TARGET_INSTANCE_ID% +exit /b 0 \ No newline at end of file diff --git a/scripts/stop-one.py b/scripts/stop-one.py new file mode 100644 index 00000000..cb752af8 --- /dev/null +++ b/scripts/stop-one.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""Stop exactly ONE API replica selected by TARGET_INSTANCE_ID — called by resilience.py failover test.""" +import subprocess +import sys +import os + +def main(): + target = os.environ.get("TARGET_INSTANCE_ID") + if not target: + print("TARGET_INSTANCE_ID not set", file=sys.stderr) + return 2 + + # Change to repo root + repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.chdir(repo_root) + + # Stop the specific API service by its compose service name + result = subprocess.run(["docker", "compose", "stop", "--timeout", "5", target], capture_output=True) + if result.returncode != 0: + print(f"docker compose stop {target} failed: {result.stderr.decode()}", file=sys.stderr) + return 1 + return 0 + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..dbe96e5e --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Stop exactly ONE API replica selected by TARGET_INSTANCE_ID and leave it stopped. +# Used by tests/resilience.py failover scenario. +set -eu + +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +# Resolve compose project directory regardless of invocation cwd. +cd "$(dirname "$0")/.." + +# INSTANCE_ID values are the compose service names (api-1, api-2, ...). +exec docker compose stop --timeout 5 "$TARGET_INSTANCE_ID" \ No newline at end of file diff --git a/tests/concurrent_idempotency.py b/tests/concurrent_idempotency.py new file mode 100644 index 00000000..77b7a5b5 --- /dev/null +++ b/tests/concurrent_idempotency.py @@ -0,0 +1,40 @@ +"""Concurrent replay of one idempotency key through the public load balancer.""" +import threading +import uuid +from concurrent.futures import ThreadPoolExecutor + +from client import Client, Failure, arguments, check, run + + +def main(): + args = arguments("Concurrent idempotency acceptance test") + base = args.base_url + alice, bob, chat = None, None, None + setup = Client(base, args.ca_file) + alice, bob, eve, chat = setup.bootstrap() + key = uuid.uuid4().hex + barrier = threading.Barrier(16) + + def send(_): + client = Client(base, args.ca_file, timeout=10) + barrier.wait() + return client.message(alice, chat, "одновременный повтор", key=key)["json"] + + with ThreadPoolExecutor(max_workers=16) as pool: + messages = list(pool.map(send, range(16))) + + ids = [message["id"] for message in messages] + check(len(set(ids)) == 1, "concurrent retry created duplicate message IDs") + history = setup.call( + "GET", + f"/api/v1/chats/{chat['id']}/messages?limit=100", + actor=bob, + schema="MessagePage", + )["json"]["items"] + matching = [message for message in history if message["id"] == ids[0]] + check(len(matching) == 1, "concurrent retry stored not exactly one message") + print("PASS: concurrent idempotency stored exactly one message") + + +if __name__ == "__main__": + run(main)