diff --git a/.dockerignore b/.dockerignore index bc16e556..6a8b8225 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,20 +1,28 @@ +# В образ попадает только то, что нужно рантайму. Всё лишнее исключаем: +# уменьшает контекст сборки, ускоряет build и не даёт утечь .env/секретам. .git -.github +.gitignore +.dockerignore +Dockerfile +Dockerfile.example .env .env.* !.env.example -secrets -certs -volumes -data -backups -*.key -*.pem -*.p12 -*.pfx -*.jks -.venv -__pycache__ -node_modules -evidence -.DS_Store +.venv/ +__pycache__/ +*.py[cod] +tests/ +student-tests/ +scripts/ +contracts/ +evidence/ +*.md +.github/ +lab.json +requirements-dev.txt +compose.yaml +compose.example.yaml +examples/ +Makefile +MAINTAINERS.md +infra/ diff --git a/.env.example b/.env.example index d32b9be0..8fe93aff 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +1,30 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# Скопируйте в .env для ЛОКАЛЬНОГО учебного стенда; .env никогда не коммитится. +# Пароль ниже — синтетический пример, задайте свой. APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab -SESSION_TTL_SECONDS=3600 -# 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: + +# PostgreSQL — источник истины (пользователи, чаты, сообщения, сессии, ключи идемпотентности). +# Compose собирает из них DATABASE_URL. Вне compose: DATABASE_URL или DATABASE_URL_FILE. +POSTGRES_DB=messenger +POSTGRES_USER=messenger +POSTGRES_PASSWORD=change-me-local-only + +# Сессии в PostgreSQL, Redis — общий кэш сессий для всех реплик. SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url +SESSION_TTL_SECONDS=3600 +SESSION_CACHE_TTL_SECONDS=60 +# CACHE_URL (или CACHE_URL_FILE) задаёт compose: redis://redis:6379/0. + +# lab3: число реплик API за балансировщиком и срок хранения Idempotency-Key. API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 + +# Пул соединений и таймауты +DB_POOL_MAX=10 +DB_POOL_TIMEOUT=3 +DB_STATEMENT_TIMEOUT_MS=5000 +REDIS_TIMEOUT=0.5 +SHUTDOWN_TIMEOUT=10 + +LOG_LEVEL=info diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..0237de68 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,27 @@ +# syntax=docker/dockerfile:1 + +# ---- Stage 1: builder: зависимости ставим отдельно, в рантайм несём только результат +FROM python:3.12.7-slim-bookworm AS builder +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1 +WORKDIR /app +COPY requirements.txt . +RUN pip install --prefix=/install -r requirements.txt + +# ---- Stage 2: runtime +FROM python:3.12.7-slim-bookworm AS runtime +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 \ + APP_HOST=0.0.0.0 APP_PORT=8080 SHUTDOWN_TIMEOUT=10 +RUN useradd --create-home --uid 10001 appuser +WORKDIR /app +COPY --from=builder /install /usr/local +COPY app ./app +COPY migrations ./migrations +USER appuser +EXPOSE 8080 +# /health/ready проверяет PostgreSQL: без БД контейнер станет unhealthy. +HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \ + CMD python -c "import os,urllib.request,sys; \ +u='http://127.0.0.1:'+os.getenv('APP_PORT','8080')+'/health/ready'; \ +sys.exit(0 if urllib.request.urlopen(u,timeout=2).status==200 else 1)" || exit 1 +# exec-форма: uvicorn — PID 1 и сам получает SIGTERM от docker stop. +CMD ["python", "-m", "app"] diff --git a/REPORT.md b/REPORT.md index c2679005..7a2f9b60 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,116 @@ # Отчёт — лабораторная 3 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Санжаровский, БВТ2304 +- Целевая оценка: **4** (трек 5 не заявлен) +- Commit/PR: ветка `solution/bvt2304-sanzharovskiy` форка `Anatoly01/mtusi2026lab3`, PR в `mtusi2026/mtusi2026lab3` +- Источники и библиотеки: FastAPI, uvicorn, psycopg 3 + psycopg-pool, argon2-cffi, redis-py; HAProxy 3.0 (resolvers, server-template, httpchk); документация Docker Compose (deploy.replicas, resources, healthcheck); PostgreSQL (INSERT … ON CONFLICT, блокировки уникального индекса). +- Помощь ИИ: Claude (Anthropic) помогал проектировать и писать код, конфигурацию, тесты и отчёт. Решения я разобрал и могу объяснить; результаты получены реальными запусками (файлы в `evidence/`). ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужно: Docker Desktop (Compose v2), Python 3.9+ для тестов. Образы закреплены: `python:3.12.7-slim-bookworm`, `postgres:16.4-alpine`, `redis:7.4.1-alpine`, `haproxy:3.0.5-alpine`. + +```sh +cp .env.example .env # Windows: copy .env.example .env ; задать свой POSTGRES_PASSWORD +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +# порядок старта: postgres(healthy) → migrate (однократно, exit 0) → api ×2 → lb +curl -i http://localhost:8080/health/ready # 200 + X-Instance-Id +make check +make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +scripts/restore-api.sh # вернуть остановленную реплику; повторить failover для другой +python student-tests/idempotency.py --base-url http://localhost:8080 +python student-tests/failover_each.py --base-url http://localhost:8080 --output evidence/failover-each.json +python student-tests/rolling_update.py --base-url http://localhost:8080 --output evidence/rolling-update.json +``` + +Windows: вместо `make` — `python tests\smoke.py …`, `python tests\resilience.py --mode failover --action-script scripts\stop-one.cmd …`, хуки `scripts\restart.cmd`, `scripts\stop-one.cmd`, `scripts\restore-api.cmd`. + +Остановка без потери данных: `docker compose --env-file .env down`. Намеренное удаление учебных данных: `docker compose --env-file .env down -v`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +``` +клиент ──▶ lb (HAProxy, 127.0.0.1:8080) ──roundrobin──▶ api #1 ─┐ + │ httpchk /health/ready раз в 0,5 c ├─▶ postgres (источник истины, volume pgdata) + │ DNS docker: api:8080 → все реплики ├─▶ redis (общий кэш сессий) + └──────────────────────────────────▶ api #2 ─┘ +migrate (однократно до api): python -m app.migrate +``` + +| Роль | Service | Версия | Health/readiness | Volume | Порт | Credentials | +| --- | --- | --- | --- | --- | --- | --- | +| load_balancer | `lb` | `haproxy:3.0.5-alpine` | `/healthz` на 8404; backend-проверка `/health/ready` | нет | `127.0.0.1:8080` (и 8081 для профиля ttl) | нет | +| api ×2 | `api` (`deploy.replicas: 2`) | образ из `Dockerfile` | `/health/ready` (БД + миграции), Docker healthcheck 5 c | нет (stateless) | только внутренняя сеть, `expose` 8080 | env из `.env` | +| миграции | `migrate` | тот же образ, `python -m app.migrate` | exit 0 → старт api | нет | — | env | +| postgres | `postgres` | `postgres:16.4-alpine` | `pg_isready` | `pgdata` | внутренняя | `POSTGRES_*` | +| redis | `redis` | `redis:7.4.1-alpine` | `redis-cli ping` | нет (кэш) | внутренняя | нет | + +**Что перенесено из lab2:** PostgreSQL как источник истины, сессии в PostgreSQL + общий Redis-кэш, Argon2id, Basic → Bearer, атомарный logout с инвалидацией кэша, 415 для не-JSON, keyset-пагинация, пул и таймауты. + +**Что добавлено в lab3:** +- **Реплики без локального состояния.** Сессии, данные и ключи идемпотентности общие (PostgreSQL/Redis), поэтому запросы одного пользователя можно обслуживать любой репликой без повторного входа и без sticky sessions. +- **`X-Instance-Id`** в каждом ответе API (включая ошибки и health) — hostname контейнера, то есть короткий ID контейнера Docker. По нему `stop-one.sh` находит и останавливает именно эту реплику (с проверкой, что контейнер принадлежит сервису `api`). +- **Общая идемпотентность** (`migrations/0002_idempotency.sql`, `app/repo.py: send_message_idempotent`). Таблица `idempotency_keys`, PK `(user_id, chat_id, idem_key)` — область «пользователь + чат + ключ» (метод и путь фиксированы). В одной транзакции: `INSERT … ON CONFLICT DO NOTHING` ключа (с хэшем канонического тела) и `INSERT` сообщения. Конкурентный повтор через другую реплику ждёт COMMIT первого на уникальном индексе, затем читает сохранённый результат: тот же 201 и тот же Message. Другое тело → 409. Ошибка/5xx откатывает и ключ, и сообщение, поэтому временная ошибка не фиксируется как результат. Повтор заново проверяет сессию и доступ. Ключ старше `IDEMPOTENCY_TTL_SECONDS` (24 ч) используется заново. Нет/неверный ключ → 400. +- **Миграции однократно**: отдельный сервис `migrate`, реплики стартуют только после его успешного завершения (`service_completed_successfully`), у реплик `MIGRATE_ON_START=false`. Дополнительно `pg_advisory_lock` исключает гонку. `0002` только добавляет таблицу — совместима с работающей версией lab2. +- **Балансировщик**: HAProxy, `server-template api 6 api:8080` + `resolvers docker` — новые/удалённые контейнеры подхватываются через DNS Docker без перезапуска LB. Повтор только при ошибке установки соединения (`retries 3`, `option redispatch`, `timeout connect 500ms`) — запрос ещё не отправлен, это безопасно и для POST. Если не готова ни одна реплика (упала общая БД), запросы идут в живые процессы через `backup`-серверы без проверки, чтобы API ответил по контракту (401, 503 в формате ошибки, live 200), а не голым 503 балансировщика. У этих серверов `resolve-opts allow-dup-ip`: без него HAProxy не отдаёт IP, уже занятый основным сервером, второму серверу бэкенда, и резервные остаются без адреса (так и было на первом прогоне: outage 9/11). +- **Graceful shutdown**: `docker stop` → SIGTERM → uvicorn сразу перестаёт принимать соединения и дожидается текущих запросов (до `SHUTDOWN_TIMEOUT=10` c, `stop_grace_period: 15s`). Новые соединения к остановленной реплике отклоняются, и HAProxy повторяет их на другой. +- **Лимиты**: api 0.5 CPU / 256 МБ, postgres 1 CPU / 512 МБ, redis 0.25 CPU / 96 МБ, lb 0.5 CPU / 128 МБ, migrate 0.5 CPU / 256 МБ. `container_name` не задан, порты api наружу не публикуются. + +**Обнаружение отказа.** Активная проверка `GET /health/ready` раз в `inter 500ms`, `fall 2` → недоступная/неготовая реплика исключается через ≈ 1–1,5 c; возвращается через `rise 2` (≈ 1 c после готовности). Остановленный контейнер отклоняет соединения сразу, и такие запросы HAProxy повторяет на другой реплике ещё до срабатывания проверки. Остановка/удаление контейнера видна через DNS не позже `hold` 5 c. + +**Соответствие `.env.example`:** `API_REPLICAS` → `deploy.replicas`; `IDEMPOTENCY_TTL_SECONDS` → срок ключа; `SESSION_STORE=postgres` — сессии в PostgreSQL; `DATABASE_URL_FILE`/`CACHE_URL_FILE` поддерживаются (файл приоритетнее переменной); в compose `DATABASE_URL` собирается из `POSTGRES_*`, `CACHE_URL=redis://redis:6379/0`. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Стенд: ПК с Windows и Docker Desktop, стек из `compose.yaml` как есть (`API_REPLICAS=2`, HAProxy 3.0.5, PostgreSQL 16.4, Redis 7.4), тесты запускались с хоста через LB `http://localhost:8080`. Исключение — опыт с SIGKILL (`evidence/failover-kill9.*`): он снят на отдельном Linux-стенде без Docker (те же код и конфигурация балансировки, реплики — процессы `api-a`/`api-b`). -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл | +| --- | --- | --- | --- | +| Публичный smoke | `make check`, `make validate`, `make test` | PASS (профиль lab3: X-Instance-Id, Idempotency-Key, повтор, 409, 400) | `evidence/smoke.txt` | +| ≥2 реплики, одна точка входа, общая БД и сессии | `docker compose ps`; `curl -i …/health/live` несколько раз | ответы чередуются между двумя X-Instance-Id; `idempotency.py` фиксирует ≥2 реплики на одной сессии | `evidence/idempotency.txt` | +| Отказ одной реплики (failover) | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | PASS дважды (остановлены разные реплики): 2 реплики до отказа, 0 неудачных попыток, первая успешная запись через 1,75 c и 1,86 c | `evidence/failover.txt` | +| Сохранность после рестарта всего стенда | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS: тот же токен читает те же данные | `evidence/persistence.txt` | +| Идемпотентность, в т.ч. конкурентная через разные реплики | `student-tests/idempotency.py` | 20 параллельных запросов с одним ключом → 20×201, один id, 2 реплики, одно сообщение; другой body → 409; без/неверный ключ → 400; другой чат/пользователь — независимо; повтор после таймаута → одно сообщение | `evidence/idempotency.txt` | +| Поочерёдная остановка каждой реплики, RPS/ошибки/восстановление | `student-tests/failover_each.py` (`docker stop`) и опыт с SIGKILL | см. таблицу ниже | `evidence/failover-each.json`, `evidence/failover-kill9.json` | +| Health/readiness, таймауты, SIGTERM, исключение backend | `infra/haproxy/haproxy.cfg`, `compose.yaml` | проверка раз в 0,5 c, исключение ≈1–1,5 c; при остановке реплики — пауза ≤0,48 c | раздел «Архитектура» | +| Лимиты CPU/RAM, нет обхода LB, нет container_name | `compose.yaml`, `docker compose config` | у всех сервисов `deploy.resources.limits`; у api только `expose` | `compose.yaml` | +| Rolling update под нагрузкой | `student-tests/rolling_update.py` | 9/9 PASS: 2 старые реплики заменены по одной за 18,6 c; ошибок 0 (до/во время/после: 158/142/169 RPS), макс. пауза 0,47 c, все реплики на новом образе, старые трафик не получают, 0 потерь и дублей | `evidence/rolling-update.json` | +| Миграции однократно и совместимо | сервис `migrate`; `python -m app.migrate` на пустой, повторно и на базе lab2 | `['0001_init','0002_idempotency']` → `nothing` → на базе lab2 добавляется только `0002` | `evidence/migrations.txt` | +| Сохранено из lab2 | `run.py` (25), `race.py`, `expiry.py`, `outage.py`, `logout_cache.py`, `rollback_check.py` | всё PASS через LB: run+race, expiry 4/4, outage 11/11, logout_cache 6/6, rollback PASS | `evidence/student-tests.txt` и др. | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +**Поочерёдная остановка реплик под нагрузкой** (`failover_each.py`, Docker): 4 потока в замкнутом цикле пишут сообщения через LB, при неудаче повторяют тот же запрос с тем же Idempotency-Key; 4 c до остановки + 12 c после; реплика останавливается `docker stop` (SIGTERM) и затем возвращается. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +| Остановка | Реплика | RPS до | RPS 10 c после | Ошибки после | Макс. пауза без успешной записи | Возврат в LB | Потери / дубли | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `docker stop` | b5c5b15326cd | 125 | 99 | 1 | 0,18 c | 3,7 c | 0 / 0 | +| `docker stop` | c2fc366c1f6b | 155 | 92 | 1 | 0,48 c | 3,8 c | 0 / 0 | +| SIGKILL (Linux-стенд) | api-a | 384 | 343 | 3 | 0,07 c | 2,6 c | 0 / 0 | +| SIGKILL (Linux-стенд) | api-b | 379 | 326 | 3 | 0,05 c | 2,1 c | 0 / 0 | + +При `docker stop` ошибка одна: запрос, попавший на реплику в момент закрытия соединения; клиент повторил его с тем же ключом, в истории ровно одно сообщение. При SIGKILL обрываются запросы, которые были в работе (по одному на поток), — их тоже безопасно повторяют с тем же ключом. RPS после остановки ниже, потому что остаётся одна реплика с лимитом 0,5 CPU; клиент на той же машине, closed loop, поэтому это не предел системы. + +**Rolling update** (`rolling_update.py`): для каждой старой реплики поднимается новая (`--scale api=3 --no-recreate`), скрипт ждёт healthy и попадания в LB, затем `docker stop` + `docker rm` старой. Обновление 18,6 c, 3620 сообщений записано под нагрузкой, 0 ошибок, 0 потерь и дублей. + +**Нагрузка** (`tests/load.py --duration 15 --concurrency 4`, 2 реплики по 0,5 CPU): 100 RPS, 0 ошибок, p50 14,3 мс, p95 83,3 мс, p99 169,5 мс (`evidence/load.json`). + +| Воздействие | Ожидаем | Наблюдали | Восстановление / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| остановка одной реплики | чтение/запись продолжаются ≤10 c | пауза ≤0,48 c, 1 повтор, failover-тест PASS | данные и сессия на месте | +| падение процесса (SIGKILL) | краткие ошибки, безопасный повтор | 3 ошибки, повтор с тем же ключом, 0 дублей (Linux-стенд) | ≤0,07 c | +| рестарт всего стенда | данные и токен сохраняются | persistence PASS | несколько секунд до ready | +| остановка Redis | работа через PostgreSQL | outage PASS | кэш наполняется заново | +| остановка PostgreSQL | 503 в формате контракта, аноним 401 | outage 11/11 PASS (через backup-путь LB) | после старта БД тот же токен работает | +| logout при приостановленном Redis | без ложного 204 | 503, после восстановления 204 → 401 | — | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Единичные точки отказа: LB, PostgreSQL и Redis по одному экземпляру на одном хосте. Отказ узла (хоста) целиком не переживается — это проверка отказа процесса/контейнера API. +- `X-Instance-Id` — короткий ID контейнера (допустимо в lab3; в lab7 нужен случайный alias без раскрытия внутренних имён). +- Таблица `idempotency_keys` растёт: просроченные ключи переиспользуются, но фоновой очистки старше 24 ч нет (индекс по `created_at` для неё уже есть). +- Rolling update в Compose реализован скриптом (`rolling_update.py`): сначала поднимается новая реплика, потом останавливается старая. Это не встроенный механизм Swarm/Kubernetes. +- `created_at` назначает реплика по своим часам; на одном хосте часы общие, при нескольких хостах нужен общий источник времени. diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/__main__.py b/app/__main__.py new file mode 100644 index 00000000..31667101 --- /dev/null +++ b/app/__main__.py @@ -0,0 +1,22 @@ +""" +Точка входа контейнера: `python -m app`. Настройки — из окружения (app/config.py). +uvicorn ловит SIGTERM: перестаёт принимать запросы и дожидается текущих +(до SHUTDOWN_TIMEOUT), затем закрывает пул БД и соединение с Redis. +""" +import logging + +import uvicorn + +from .config import settings + +if __name__ == "__main__": + logging.basicConfig(level=settings.log_level.upper(), + format="%(asctime)s %(levelname)s %(name)s %(message)s") + uvicorn.run( + "app.main:app", + host=settings.host, + port=settings.port, + timeout_graceful_shutdown=settings.shutdown_timeout, + access_log=False, # свой лог в middleware: без query, токенов и тел + log_level=settings.log_level, + ) diff --git a/app/config.py b/app/config.py new file mode 100644 index 00000000..2fbfa55b --- /dev/null +++ b/app/config.py @@ -0,0 +1,62 @@ +""" +Конфигурация только из переменных окружения (ничего не зашито в код и образ). +""" +from __future__ import annotations +import os +import socket +from dataclasses import dataclass + + +def _int(name: str, default: int) -> int: + return int(os.getenv(name, str(default))) + + +def _float(name: str, default: float) -> float: + return float(os.getenv(name, str(default))) + + +def _secret(name: str, default: str = "") -> str: + """Значение из NAME_FILE (Docker secret, файл) или из переменной NAME. + Файл приоритетнее: так credentials не видны в `docker inspect`.""" + path = os.getenv(name + "_FILE") + if path: + with open(path, encoding="utf-8") as f: + return f.read().strip() + return os.getenv(name, default) + + +@dataclass(frozen=True) +class Settings: + # HTTP + host: str = os.getenv("APP_HOST", "0.0.0.0") + port: int = _int("APP_PORT", 8080) + shutdown_timeout: int = _int("SHUTDOWN_TIMEOUT", 10) + log_level: str = os.getenv("LOG_LEVEL", "info") + # Имя реплики для X-Instance-Id: INSTANCE_ID или hostname контейнера + # (в Docker это короткий ID контейнера — по нему stop-one.sh находит реплику). + instance_id: str = os.getenv("INSTANCE_ID") or socket.gethostname() + + # PostgreSQL — источник истины + database_url: str = _secret( + "DATABASE_URL", "postgresql://messenger:devpass@127.0.0.1:5432/messenger") + db_pool_min: int = _int("DB_POOL_MIN", 1) + db_pool_max: int = _int("DB_POOL_MAX", 10) # ограниченный пул + db_pool_timeout: float = _float("DB_POOL_TIMEOUT", 3.0) # ждать свободное соединение + db_connect_timeout: int = _int("DB_CONNECT_TIMEOUT", 3) + db_statement_timeout_ms: int = _int("DB_STATEMENT_TIMEOUT_MS", 5000) + migrate_on_start: bool = os.getenv("MIGRATE_ON_START", "true").lower() == "true" + + # Сессии + session_ttl_seconds: int = _int("SESSION_TTL_SECONDS", 3600) + + # Идемпотентность POST сообщений: сколько хранить ключ (контракт: 24 часа) + idempotency_ttl_seconds: int = _int("IDEMPOTENCY_TTL_SECONDS", 86400) + + # Redis/Valkey — кэш сессий (не источник истины). Пусто = кэш выключен. + # Имя из skeleton — CACHE_URL(_FILE); REDIS_URL оставлено как синоним. + redis_url: str = _secret("CACHE_URL") or _secret("REDIS_URL") + redis_timeout: float = _float("REDIS_TIMEOUT", 0.5) + session_cache_ttl_seconds: int = _int("SESSION_CACHE_TTL_SECONDS", 60) + + +settings = Settings() diff --git a/app/db.py b/app/db.py new file mode 100644 index 00000000..3a3368e1 --- /dev/null +++ b/app/db.py @@ -0,0 +1,50 @@ +""" +Пул соединений с PostgreSQL. + +- Пул ограничен (DB_POOL_MAX): при нагрузке запросы ждут свободное соединение + не дольше DB_POOL_TIMEOUT, а не открывают соединения без предела. +- connect_timeout и statement_timeout: зависший запрос или недоступная БД + не держат обработчик бесконечно — клиент получает 503. +- Все запросы параметризованы (%s), SQL-инъекция невозможна. +""" +from __future__ import annotations +from psycopg_pool import AsyncConnectionPool + +from .config import settings + +pool: AsyncConnectionPool | None = None + + +def make_pool() -> AsyncConnectionPool: + return AsyncConnectionPool( + conninfo=settings.database_url, + min_size=settings.db_pool_min, + max_size=settings.db_pool_max, + timeout=settings.db_pool_timeout, + kwargs={ + "connect_timeout": settings.db_connect_timeout, + "options": f"-c statement_timeout={settings.db_statement_timeout_ms}", + "application_name": "messenger-api", + }, + # Перед выдачей соединение проверяется (SELECT 1 на уровне протокола): + # после рестарта PostgreSQL «мёртвые» соединения отбрасываются, а не дают 503. + check=AsyncConnectionPool.check_connection, + open=False, + ) + + +async def open_pool() -> None: + global pool + pool = make_pool() + # wait=False: API стартует, даже если БД ещё поднимается; /health/ready это покажет. + await pool.open(wait=False) + + +async def close_pool() -> None: + if pool is not None: + await pool.close() + + +def get_pool() -> AsyncConnectionPool: + assert pool is not None, "pool is not opened" + return pool diff --git a/app/main.py b/app/main.py new file mode 100644 index 00000000..94abb58b --- /dev/null +++ b/app/main.py @@ -0,0 +1,388 @@ +""" +HTTP-слой мессенджера (lab3). + +Клиент → LB (HAProxy) → эта реплика API (их ≥2, взаимозаменяемы) + → PostgreSQL (источник истины) + Redis (общий кэш сессий) + +lab2: пароль Argon2id, вход Basic → Bearer-сессия в PostgreSQL, X-User-Id игнорируется. +lab3: X-Instance-Id в каждом ответе; POST сообщения требует Idempotency-Key, + идемпотентность общая для всех реплик (таблица idempotency_keys); + у реплики нет локального состояния, от которого зависит корректность. +""" +from __future__ import annotations +import base64 +import binascii +import logging +import re +import time +import uuid +from contextlib import asynccontextmanager + +import psycopg +from fastapi import Depends, FastAPI, Header, Query, Request +from fastapi.concurrency import run_in_threadpool +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, Response +from psycopg_pool import PoolTimeout +from pydantic import BaseModel, field_validator +from starlette.exceptions import HTTPException as StarletteHTTPException + +from . import db, repo, security, sessions +from .config import settings +from .migrate import migrate + +logger = logging.getLogger("messenger") + +USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") +IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}") +BEARER_CHALLENGE = 'Bearer realm="messenger"' +BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' + + +@asynccontextmanager +async def lifespan(app: FastAPI): + if settings.migrate_on_start: + try: + applied = await migrate() + logger.info("migrations: %s", applied or "up to date") + except psycopg.OperationalError as exc: + # БД ещё не готова: API всё равно стартует, /health/ready покажет 503. + logger.warning("migrations skipped, database unavailable: %s", type(exc).__name__) + await db.open_pool() + sessions.init_redis() + yield + await sessions.close_redis() + await db.close_pool() + + +app = FastAPI(title="MTUSI Messenger — lab2", lifespan=lifespan) + + +# ============================================================================ +# 1. ЕДИНЫЙ ФОРМАТ ОШИБОК {"error":{"code","message","request_id"}} +# ============================================================================ +class ApiError(Exception): + def __init__(self, status: int, code: str, message: str, headers: dict | None = None): + self.status, self.code, self.message, self.headers = status, code, message, headers or {} + + +def error_response(request: Request, status: int, code: str, message: str, + headers: dict | None = None) -> JSONResponse: + rid = getattr(request.state, "request_id", str(uuid.uuid4())) + return JSONResponse( + status_code=status, + content={"error": {"code": code, "message": message, "request_id": rid}}, + headers={"X-Request-Id": rid, "X-Instance-Id": settings.instance_id, **(headers or {})}, + ) + + +@app.exception_handler(ApiError) +async def handle_api_error(request: Request, exc: ApiError): + return error_response(request, exc.status, exc.code, exc.message, exc.headers) + + +@app.exception_handler(RequestValidationError) +async def handle_validation(request: Request, exc: RequestValidationError): + return error_response(request, 400, "invalid_request", "invalid request body or parameters") + + +@app.exception_handler(StarletteHTTPException) +async def handle_http(request: Request, exc: StarletteHTTPException): + # Только коды из enum контракта (contracts/openapi.json → Error.code). + code = {401: "unauthorized", 404: "not_found", 409: "conflict", + 413: "payload_too_large", 415: "unsupported_media_type", + 429: "rate_limited", 503: "unavailable"}.get( + exc.status_code, "internal_error" if exc.status_code >= 500 else "invalid_request") + return error_response(request, exc.status_code, code, str(exc.detail)) + + +@app.exception_handler(psycopg.OperationalError) +@app.exception_handler(PoolTimeout) +async def handle_db_down(request: Request, exc: Exception): + # БД недоступна или не ответила за таймаут: ограниченная ошибка, а не зависание. + logger.warning("database unavailable: %s", type(exc).__name__) + return error_response(request, 503, "unavailable", "service temporarily unavailable") + + +@app.exception_handler(Exception) +async def handle_unexpected(request: Request, exc: Exception): + logger.exception("unexpected error") + return error_response(request, 500, "internal_error", "internal error") + + +# ============================================================================ +# 2. X-Request-Id, X-Instance-Id + лог без тела запроса, токенов и паролей +# ============================================================================ +@app.middleware("http") +async def add_request_id(request: Request, call_next): + rid = str(uuid.uuid4()) + request.state.request_id = rid + start = time.monotonic() + response = await call_next(request) + response.headers["X-Request-Id"] = rid + response.headers["X-Instance-Id"] = settings.instance_id # какая реплика ответила + logger.info("rid=%s %s %s -> %s %sms", rid, request.method, request.url.path, + response.status_code, round((time.monotonic() - start) * 1000, 1)) + return response + + +# ============================================================================ +# 3. АУТЕНТИФИКАЦИЯ +# Bearer — для всех бизнес-запросов. Basic — только на POST /auth/sessions. +# X-User-Id больше ничего не значит и ни на что не влияет. +# ============================================================================ +def unauthorized(message: str = "invalid or missing bearer token") -> ApiError: + return ApiError(401, "unauthorized", message, {"WWW-Authenticate": BEARER_CHALLENGE}) + + +def _bearer_token(request: Request) -> str: + auth = request.headers.get("authorization", "") + scheme, _, token = auth.partition(" ") + token = token.strip() + if scheme.lower() != "bearer" or not token or len(token) > 512: + raise unauthorized() + return token + + +async def current_user(request: Request) -> dict: + """Зависимость FastAPI: выполняется ДО разбора тела → сначала 401, потом 400.""" + token = _bearer_token(request) + user = await sessions.resolve(db.get_pool(), token, repo.get_user) + if user is None: + raise unauthorized() + request.state.token = token + return user + + +def _parse_basic(request: Request) -> tuple[str, str]: + bad = ApiError(401, "unauthorized", "invalid credentials", {"WWW-Authenticate": BASIC_CHALLENGE}) + scheme, _, value = request.headers.get("authorization", "").partition(" ") + if scheme.lower() != "basic" or not value: + raise bad + try: + decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8") + except (binascii.Error, UnicodeDecodeError): + raise bad + username, sep, password = decoded.partition(":") # двоеточие в пароле допустимо + if not sep or not username.isascii() or not (12 <= len(password) <= 128): + raise bad + return username, password + + +def require_json(request: Request) -> None: + """Тип тела проверяем ДО валидации тела: не JSON → 415, а не 400. + Подключается после current_user, поэтому без токена по-прежнему сначала 401. + Параметры вроде '; charset=utf-8' допустимы.""" + media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() + if media_type != "application/json": + raise ApiError(415, "unsupported_media_type", "Content-Type must be application/json") + + +# ============================================================================ +# 4. МОДЕЛИ ВВОДА +# ============================================================================ +class CreateUser(BaseModel): + model_config = {"extra": "forbid"} + username: str + display_name: str + password: str + + @field_validator("username") + @classmethod + def check_username(cls, v: str) -> str: + if not USERNAME_RE.match(v): + raise ValueError("username must match [a-z0-9_]{3,32}") + return v + + @field_validator("display_name") + @classmethod + def check_display_name(cls, v: str) -> str: + if not (1 <= len(v) <= 100) or not v.strip(): + raise ValueError("display_name must be 1..100 non-blank chars") + return v + + @field_validator("password") + @classmethod + def check_password(cls, v: str) -> str: + if not (12 <= len(v) <= 128) or not v.strip(): + raise ValueError("password must be 12..128 chars") + return v + + +class CreateChat(BaseModel): + model_config = {"extra": "forbid"} + title: str + member_ids: list[str] + + @field_validator("title") + @classmethod + def check_title(cls, v: str) -> str: + if not (1 <= len(v) <= 100) or not v.strip(): + raise ValueError("title must be 1..100 non-blank chars") + return v + + +class CreateMessage(BaseModel): + model_config = {"extra": "forbid"} + text: str + + @field_validator("text") + @classmethod + def check_text(cls, v: str) -> str: + if not (1 <= len(v) <= 4000) or not v.strip(): + raise ValueError("text must be 1..4000 non-blank chars") + return v + + +def parse_uuid(value: str, what: str) -> uuid.UUID: + try: + return uuid.UUID(value) + except ValueError: + raise ApiError(400, "invalid_request", f"{what} is not a valid uuid") + + +# ============================================================================ +# 5. ENDPOINTS +# ============================================================================ +@app.get("/health/live") +async def health_live(): + return {"status": "ok"} + + +@app.get("/health/ready") +async def health_ready(request: Request): + # Критичная зависимость — только PostgreSQL. Redis — кэш: его отказ не делает API неготовым. + try: + async with db.get_pool().connection() as conn: + await conn.execute("SELECT 1 FROM schema_migrations LIMIT 1") + except (psycopg.Error, PoolTimeout): + return error_response(request, 503, "unavailable", "database is not ready") + return {"status": "ok"} + + +# -------- users и сессии -------- +@app.post("/api/v1/users", status_code=201) +async def create_user(body: CreateUser, _json: None = Depends(require_json)): + # Argon2 намеренно медленный — считаем в пуле потоков, чтобы не блокировать event loop. + password_hash = await run_in_threadpool(security.hash_password, body.password) + async with db.get_pool().connection() as conn: + try: + return await repo.create_user(conn, body.username, body.display_name, password_hash) + except repo.UsernameTaken: + raise ApiError(409, "conflict", "username already taken") + + +@app.post("/api/v1/auth/sessions", status_code=201) +async def create_session(request: Request): + username, password = _parse_basic(request) + async with db.get_pool().connection() as conn: + row = await repo.get_credentials(conn, username) + stored_hash = row[4] if row else None + # Проверяем хэш даже для несуществующего пользователя — одинаковое время ответа. + ok = await run_in_threadpool(security.verify_password, stored_hash, password) + if not ok: + raise ApiError(401, "unauthorized", "invalid credentials", {"WWW-Authenticate": BASIC_CHALLENGE}) + user = repo.user_out(row) + async with db.get_pool().connection() as conn: + if security.needs_rehash(stored_hash): + await repo.update_password_hash(conn, row[0], await run_in_threadpool(security.hash_password, password)) + token, expires_at = await sessions.create_session(conn, row[0]) + return {"token": token, "token_type": "Bearer", "expires_at": repo.iso(expires_at), "user": user} + + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +async def delete_session(request: Request, user: dict = Depends(current_user)): + try: + revoked = await sessions.revoke(db.get_pool(), request.state.token) + except sessions.CacheUnavailable: + # 204 только при гарантированном отзыве; иначе ограниченная ошибка, повторить позже. + raise ApiError(503, "unavailable", "session cache unavailable, logout not confirmed") + if not revoked: + raise unauthorized() + return Response(status_code=204) + + +@app.get("/api/v1/users/me") +async def get_me(user: dict = Depends(current_user)): + return user + + +# -------- chats -------- +@app.post("/api/v1/chats", status_code=201) +async def create_chat(body: CreateChat, user: dict = Depends(current_user), + _json: None = Depends(require_json)): + members = body.member_ids + if not (1 <= len(members) <= 100): + raise ApiError(400, "invalid_request", "member_ids must have 1..100 items") + if len(set(members)) != len(members): + raise ApiError(400, "invalid_request", "duplicate member_ids") + ids = [parse_uuid(m, "member id") for m in members] + if uuid.UUID(user["id"]) not in ids: + raise ApiError(400, "invalid_request", "caller must be a member") + async with db.get_pool().connection() as conn: + # Одна транзакция: чат и все участники создаются вместе или не создаются вовсе. + async with conn.transaction(): + if await repo.count_existing_users(conn, ids) != len(ids): + raise ApiError(400, "invalid_request", "unknown member") + return await repo.insert_chat(conn, body.title, ids, user["id"]) + + +@app.get("/api/v1/chats") +async def list_chats(user: dict = Depends(current_user), + limit: int = Query(default=50, ge=1, le=100), + cursor: str | None = Query(default=None, min_length=1)): + async with db.get_pool().connection() as conn: + try: + items, nxt = await repo.list_chats(conn, user["id"], limit, cursor) + except ValueError: + raise ApiError(400, "invalid_request", "bad cursor") + return {"items": items, "next_cursor": nxt} + + +async def accessible_chat(conn, chat_id: str, user: dict) -> dict: + """Кривой UUID → 400. Чата нет ИЛИ ты не участник → одинаковый 404.""" + cid = parse_uuid(chat_id, "chat_id") + chat = await repo.get_chat_for_member(conn, cid, user["id"]) + if chat is None: + raise ApiError(404, "not_found", "chat not found") + return chat + + +@app.get("/api/v1/chats/{chat_id}") +async def get_chat(chat_id: str, user: dict = Depends(current_user)): + async with db.get_pool().connection() as conn: + return await accessible_chat(conn, chat_id, user) + + +# -------- messages -------- +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +async def send_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user), + _json: None = Depends(require_json), + idempotency_key: str | None = Header(default=None, alias="Idempotency-Key")): + # Ключ обязателен: без него клиент не может безопасно повторить запрос после таймаута. + if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key): + raise ApiError(400, "invalid_request", "Idempotency-Key header is required: [A-Za-z0-9._:-]{1,128}") + async with db.get_pool().connection() as conn: + # Повтор снова проверяет сессию (current_user) и доступ к чату. + chat = await accessible_chat(conn, chat_id, user) + try: + async with conn.transaction(): + # Отправитель — из сессии, а не из тела запроса. + return await repo.send_message_idempotent( + conn, chat["id"], user["id"], idempotency_key, body.text, + settings.idempotency_ttl_seconds) + except repo.IdempotencyConflict: + raise ApiError(409, "conflict", "Idempotency-Key was already used with a different request") + + +@app.get("/api/v1/chats/{chat_id}/messages") +async def list_messages(chat_id: str, user: dict = Depends(current_user), + limit: int = Query(default=50, ge=1, le=100), + cursor: str | None = Query(default=None, min_length=1)): + async with db.get_pool().connection() as conn: + chat = await accessible_chat(conn, chat_id, user) + try: + items, nxt = await repo.list_messages(conn, chat["id"], limit, cursor) + except ValueError: + raise ApiError(400, "invalid_request", "bad cursor") + return {"items": items, "next_cursor": nxt} diff --git a/app/migrate.py b/app/migrate.py new file mode 100644 index 00000000..e52cec81 --- /dev/null +++ b/app/migrate.py @@ -0,0 +1,57 @@ +""" +Версионируемые миграции: migrations/NNNN_name.sql. + +- Таблица schema_migrations хранит применённые версии → повторный запуск + ничего не дублирует (идемпотентно). +- Каждая миграция применяется в своей транзакции: либо целиком, либо никак. +- pg_advisory_lock: если стартуют несколько API одновременно, миграции + выполнит только один, остальные подождут. + +Запуск вручную: python -m app.migrate +""" +from __future__ import annotations +import asyncio +import logging +from pathlib import Path + +import psycopg + +from .config import settings + +log = logging.getLogger("messenger.migrate") +MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations" +LOCK_ID = 824_113_2026 # произвольная константа для advisory lock + + +async def migrate(conninfo: str | None = None) -> list[str]: + applied_now: list[str] = [] + async with await psycopg.AsyncConnection.connect( + conninfo or settings.database_url, + connect_timeout=settings.db_connect_timeout, autocommit=True) as conn: + await conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,)) + try: + await conn.execute( + "CREATE TABLE IF NOT EXISTS schema_migrations (" + " version text PRIMARY KEY," + " applied_at timestamptz NOT NULL DEFAULT now())") + cur = await conn.execute("SELECT version FROM schema_migrations") + done = {row[0] for row in await cur.fetchall()} + for path in sorted(MIGRATIONS_DIR.glob("*.sql")): + version = path.stem + if version in done: + continue + async with conn.transaction(): + await conn.execute(path.read_text(encoding="utf-8")) + await conn.execute( + "INSERT INTO schema_migrations (version) VALUES (%s)", (version,)) + applied_now.append(version) + log.info("migration applied: %s", version) + finally: + await conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,)) + return applied_now + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + result = asyncio.run(migrate()) + print("applied:", result or "nothing (up to date)") diff --git a/app/repo.py b/app/repo.py new file mode 100644 index 00000000..beea3e0d --- /dev/null +++ b/app/repo.py @@ -0,0 +1,219 @@ +""" +Доступ к данным в PostgreSQL. Только параметризованные запросы (%s): +значения передаются отдельно от текста SQL, инъекция невозможна. +""" +from __future__ import annotations +import base64 +import hashlib +import json +import uuid +from datetime import datetime, timezone + +from psycopg.errors import UniqueViolation + + +def iso(dt: datetime) -> str: + """RFC 3339 UTC с Z — формат контракта.""" + return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def now() -> datetime: + return datetime.now(timezone.utc) + + +# ---------------------------------------------------------------- курсор +def encode_cursor(scope: str, created_at: datetime, id_) -> str: + raw = json.dumps({"s": scope, "c": iso(created_at), "i": str(id_)}).encode() + return base64.urlsafe_b64encode(raw).decode() + + +def decode_cursor(cursor: str, scope: str) -> tuple[datetime, uuid.UUID]: + """(created_at, id) последнего показанного элемента или ValueError → 400.""" + try: + data = json.loads(base64.urlsafe_b64decode(cursor.encode())) + if data.get("s") != scope: + raise ValueError("cursor scope mismatch") + return datetime.fromisoformat(data["c"].replace("Z", "+00:00")), uuid.UUID(data["i"]) + except (ValueError, KeyError, TypeError, AttributeError) as exc: + raise ValueError("bad cursor") from exc + + +def _page(rows: list, limit: int, scope: str, key): + """rows получены с LIMIT limit+1: лишняя строка = есть следующая страница.""" + has_more = len(rows) > limit + page = rows[:limit] + next_cursor = encode_cursor(scope, *key(page[-1])) if has_more and page else None + return page, next_cursor + + +# ---------------------------------------------------------------- users +USER_COLS = "id, username, display_name, created_at" + + +def user_out(row) -> dict: + return {"id": str(row[0]), "username": row[1], "display_name": row[2], "created_at": iso(row[3])} + + +class UsernameTaken(Exception): + pass + + +async def create_user(conn, username: str, display_name: str, password_hash: str) -> dict: + try: + cur = await conn.execute( + f"INSERT INTO users (id, username, display_name, password_hash, created_at) " + f"VALUES (%s, %s, %s, %s, %s) RETURNING {USER_COLS}", + (uuid.uuid4(), username, display_name, password_hash, now())) + except UniqueViolation as exc: + # Уникальность username гарантирует БД, а не проверка «есть ли такой» + # перед вставкой: две одновременные регистрации не пройдут обе. + raise UsernameTaken() from exc + return user_out(await cur.fetchone()) + + +async def get_user(conn, user_id) -> dict | None: + cur = await conn.execute(f"SELECT {USER_COLS} FROM users WHERE id = %s", (user_id,)) + row = await cur.fetchone() + return user_out(row) if row else None + + +async def get_credentials(conn, username: str): + cur = await conn.execute( + f"SELECT {USER_COLS}, password_hash FROM users WHERE username = %s", (username,)) + return await cur.fetchone() + + +async def update_password_hash(conn, user_id, password_hash: str) -> None: + await conn.execute("UPDATE users SET password_hash = %s WHERE id = %s", (password_hash, user_id)) + + +# ---------------------------------------------------------------- chats +CHAT_SELECT = ( + "SELECT c.id, c.title, c.created_at, " + " (SELECT array_agg(m.user_id ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id) " + "FROM chats c ") + + +def chat_out(row) -> dict: + return {"id": str(row[0]), "title": row[1], + "member_ids": [str(x) for x in row[3]], "created_at": iso(row[2])} + + +async def count_existing_users(conn, ids: list[uuid.UUID]) -> int: + cur = await conn.execute("SELECT count(*) FROM users WHERE id = ANY(%s)", (ids,)) + return (await cur.fetchone())[0] + + +async def insert_chat(conn, title: str, member_ids: list[uuid.UUID], creator) -> dict: + """Чат + все участники. Вызывать внутри транзакции: либо всё, либо ничего.""" + chat_id, created = uuid.uuid4(), now() + await conn.execute( + "INSERT INTO chats (id, title, created_by, created_at) VALUES (%s, %s, %s, %s)", + (chat_id, title, creator, created)) + async with conn.cursor() as cur: + await cur.executemany( + "INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, %s)", + [(chat_id, uid, pos) for pos, uid in enumerate(member_ids)]) + return {"id": str(chat_id), "title": title, + "member_ids": [str(x) for x in member_ids], "created_at": iso(created)} + + +async def get_chat_for_member(conn, chat_id, user_id) -> dict | None: + """Чат, если он существует И пользователь в нём состоит; иначе None (→ 404).""" + cur = await conn.execute( + CHAT_SELECT + "WHERE c.id = %s AND EXISTS " + "(SELECT 1 FROM chat_members x WHERE x.chat_id = c.id AND x.user_id = %s)", + (chat_id, user_id)) + row = await cur.fetchone() + return chat_out(row) if row else None + + +async def list_chats(conn, user_id, limit: int, cursor: str | None): + scope = f"chats:{user_id}" + params: list = [user_id] + where = "" + if cursor: + c_at, c_id = decode_cursor(cursor, scope) + where = "WHERE (c.created_at, c.id) > (%s, %s) " + params += [c_at, c_id] + cur = await conn.execute( + CHAT_SELECT + "JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s " + + where + "ORDER BY c.created_at, c.id LIMIT %s", (*params, limit + 1)) + rows = await cur.fetchall() + page, nxt = _page(rows, limit, scope, key=lambda r: (r[2], r[0])) + return [chat_out(r) for r in page], nxt + + +# ---------------------------------------------------------------- messages +MSG_COLS = "id, chat_id, sender_id, text, created_at" + + +def message_out(row) -> dict: + return {"id": str(row[0]), "chat_id": str(row[1]), "sender_id": str(row[2]), + "text": row[3], "created_at": iso(row[4])} + + +# ---------------------------------------------------------------- идемпотентность +class IdempotencyConflict(Exception): + """Тот же Idempotency-Key, но другое тело запроса → 409.""" + + +def request_hash(text: str) -> bytes: + """Хэш канонического тела: порядок ключей JSON не влияет на результат.""" + canonical = json.dumps({"text": text}, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).digest() + + +async def send_message_idempotent(conn, chat_id, sender_id, key: str, text: str, + ttl_seconds: int) -> dict: + """Записать сообщение ровно один раз для (пользователь, чат, ключ). + Вызывать внутри транзакции: ключ и сообщение фиксируются вместе или никак, + поэтому ошибка (5xx) не оставляет «записанного результата». + + Конкурентные повторы через разные реплики: второй INSERT того же PK ждёт + COMMIT первого (блокировка уникального индекса в PostgreSQL), затем получает + конфликт и читает уже сохранённый результат.""" + rhash = request_hash(text) + msg_id, created = uuid.uuid4(), now() + cur = await conn.execute( + "INSERT INTO idempotency_keys (user_id, chat_id, idem_key, request_hash, message_id, created_at) " + "VALUES (%s, %s, %s, %s, %s, %s) " + "ON CONFLICT (user_id, chat_id, idem_key) DO NOTHING RETURNING 1", + (sender_id, chat_id, key, rhash, msg_id, created)) + if await cur.fetchone() is None: + cur = await conn.execute( + "SELECT request_hash, message_id, created_at < now() - make_interval(secs => %s) " + "FROM idempotency_keys WHERE user_id = %s AND chat_id = %s AND idem_key = %s FOR UPDATE", + (ttl_seconds, sender_id, chat_id, key)) + stored_hash, stored_msg, expired = await cur.fetchone() + if not expired: + if bytes(stored_hash) != rhash: + raise IdempotencyConflict() + cur = await conn.execute(f"SELECT {MSG_COLS} FROM messages WHERE id = %s", (stored_msg,)) + return message_out(await cur.fetchone()) # тот же Message, что и в первый раз + # Ключ старше TTL: используем его заново как новый. + await conn.execute( + "UPDATE idempotency_keys SET request_hash = %s, message_id = %s, created_at = %s " + "WHERE user_id = %s AND chat_id = %s AND idem_key = %s", + (rhash, msg_id, created, sender_id, chat_id, key)) + cur = await conn.execute( + f"INSERT INTO messages ({MSG_COLS}) VALUES (%s, %s, %s, %s, %s) RETURNING {MSG_COLS}", + (msg_id, chat_id, sender_id, text, created)) + return message_out(await cur.fetchone()) + + +async def list_messages(conn, chat_id, limit: int, cursor: str | None): + """Keyset-пагинация по индексу (chat_id, created_at, id): без OFFSET и без скана истории.""" + scope = f"messages:{chat_id}" + params: list = [chat_id] + where = "" + if cursor: + c_at, c_id = decode_cursor(cursor, scope) + where = "AND (created_at, id) > (%s, %s) " + params += [c_at, c_id] + cur = await conn.execute( + f"SELECT {MSG_COLS} FROM messages WHERE chat_id = %s " + where + + "ORDER BY created_at, id LIMIT %s", (*params, limit + 1)) + rows = await cur.fetchall() + page, nxt = _page(rows, limit, scope, key=lambda r: (r[4], r[0])) + return [message_out(r) for r in page], nxt diff --git a/app/security.py b/app/security.py new file mode 100644 index 00000000..c900880b --- /dev/null +++ b/app/security.py @@ -0,0 +1,46 @@ +""" +Пароли и токены. + +Пароль: Argon2id (password KDF). Он специально медленный и требует память, +поэтому перебор украденных хэшей дорог. Соль своя у каждого хэша. + +Токен сессии: 32 случайных байта (256 бит) из secrets — непрозрачная строка, +не связанная с username/UUID. В БД кладём SHA-256 от токена: для случайного +256-битного значения быстрый хэш достаточен (перебирать нечего), а утечка +таблицы sessions не даёт рабочих токенов. +""" +from __future__ import annotations +import hashlib +import secrets + +from argon2 import PasswordHasher +from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError + +_hasher = PasswordHasher() # Argon2id, параметры по умолчанию библиотеки (RFC 9106 low-memory) + +# Хэш-заглушка: проверяем пароль даже для несуществующего пользователя, +# чтобы по времени ответа нельзя было узнать, существует ли username. +_DUMMY_HASH = _hasher.hash("dummy-password-for-timing") + + +def hash_password(password: str) -> str: + return _hasher.hash(password) + + +def verify_password(password_hash: str | None, password: str) -> bool: + try: + return _hasher.verify(password_hash or _DUMMY_HASH, password) and password_hash is not None + except (VerifyMismatchError, VerificationError, InvalidHashError): + return False + + +def needs_rehash(password_hash: str) -> bool: + return _hasher.check_needs_rehash(password_hash) + + +def new_token() -> str: + return secrets.token_urlsafe(32) # 256 бит энтропии + + +def token_hash(token: str) -> bytes: + return hashlib.sha256(token.encode("utf-8")).digest() diff --git a/app/sessions.py b/app/sessions.py new file mode 100644 index 00000000..5f9ced65 --- /dev/null +++ b/app/sessions.py @@ -0,0 +1,168 @@ +""" +Сессии: PostgreSQL — источник истины, Redis/Valkey — кэш поиска сессии. + +Чтение (проверка Bearer): + 1. Ищем в Redis ключ sess:. Нашли и не истёк → пользователь. + 2. Нет в кэше / Redis недоступен → читаем sessions в PostgreSQL + (не отозвана и expires_at > now()) и кладём результат в кэш. + +Политика expiry: срок жизни сессии задаёт PostgreSQL (expires_at). +TTL ключа в Redis = min(SESSION_CACHE_TTL_SECONDS, время до expires_at), +поэтому кэш никогда не продлевает сессию. + +Инвалидация (logout) — атомарно для БД и кэша: + в одной транзакции UPDATE sessions SET revoked_at (строка блокируется), + затем DEL ключа в Redis. Если Redis не ответил — транзакция откатывается и + клиент получает 503: logout НЕ подтверждён, 204 отдаётся только когда + копии отозванной сессии в кэше гарантированно нет. + Гонка «чтение кладёт старую сессию в кэш после DEL» закрыта блокировкой: + чтение из БД идёт с FOR SHARE и кладёт в кэш, не отпуская строку, поэтому + logout ждёт окончания такого чтения и удаляет ключ уже после него. + +Отказ Redis: кэш обходится, всё читается из PostgreSQL (медленнее, но верно). +Flush/рестарт Redis: кэш пустой → сессии восстанавливаются из PostgreSQL. +Отказ PostgreSQL: новые проверки идут в БД → 503, анонимный запрос не принимается. +""" +from __future__ import annotations +import json +import logging +from datetime import datetime, timedelta, timezone + +import redis.asyncio as aioredis +from redis.exceptions import RedisError + +from .config import settings +from .security import new_token, token_hash + +log = logging.getLogger("messenger.sessions") + +_redis: aioredis.Redis | None = None + + +def init_redis() -> None: + global _redis + if settings.redis_url: + _redis = aioredis.Redis.from_url( + settings.redis_url, + socket_timeout=settings.redis_timeout, + socket_connect_timeout=settings.redis_timeout, + decode_responses=True, + ) + + +async def close_redis() -> None: + if _redis is not None: + await _redis.aclose() + + +def redis_enabled() -> bool: + return _redis is not None + + +async def redis_ping() -> bool: + if _redis is None: + return False + try: + return bool(await _redis.ping()) + except (RedisError, OSError): + return False + + +def _key(th: bytes) -> str: + return "sess:" + th.hex() + + +async def _cache_get(th: bytes) -> dict | None: + if _redis is None: + return None + try: + raw = await _redis.get(_key(th)) + except (RedisError, OSError) as exc: + log.warning("redis unavailable on read, bypassing cache: %s", type(exc).__name__) + return None + return json.loads(raw) if raw else None + + +async def _cache_put(th: bytes, user: dict, expires_at: datetime) -> None: + if _redis is None: + return + left = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + ttl = min(settings.session_cache_ttl_seconds, left) + if ttl <= 0: + return + try: + await _redis.set(_key(th), json.dumps({"user": user, "exp": expires_at.isoformat()}), ex=ttl) + except (RedisError, OSError) as exc: + log.warning("redis unavailable on write, skipping cache: %s", type(exc).__name__) + + +class CacheUnavailable(Exception): + """Redis не подтвердил удаление ключа — отзыв сессии нельзя гарантировать.""" + + +async def _cache_delete_strict(th: bytes) -> None: + """Удалить копию сессии из кэша или поднять CacheUnavailable. + Молча проглатывать ошибку нельзя: если Redis «приостановлен», ключ + переживёт сбой и после восстановления отозванный токен снова примут.""" + if _redis is None: + return + try: + await _redis.delete(_key(th)) + except (RedisError, OSError) as exc: + log.warning("redis unavailable on invalidate: %s", type(exc).__name__) + raise CacheUnavailable() from exc + + +async def create_session(conn, user_id) -> tuple[str, datetime]: + token = new_token() + now = datetime.now(timezone.utc) + expires_at = now + timedelta(seconds=settings.session_ttl_seconds) + await conn.execute( + "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) " + "VALUES (%s, %s, %s, %s)", + (token_hash(token), user_id, now, expires_at)) + return token, expires_at + + +async def resolve(pool, token: str, load_user) -> dict | None: + """Вернёт пользователя (dict) для действующего токена или None.""" + th = token_hash(token) + cached = await _cache_get(th) + if cached is not None: + if datetime.fromisoformat(cached["exp"]) > datetime.now(timezone.utc): + return cached["user"] + return None + async with pool.connection() as conn: + # FOR SHARE: пока эта транзакция не закончилась (вместе с записью в кэш), + # logout не сможет отозвать строку — он дождётся и удалит ключ после нас. + cur = await conn.execute( + "SELECT user_id, expires_at FROM sessions " + "WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now() " + "FOR SHARE", + (th,)) + row = await cur.fetchone() + if row is None: + return None + user = await load_user(conn, row[0]) + if user is None: + return None + await _cache_put(th, user, row[1]) + return user + + +async def revoke(pool, token: str) -> bool: + """Отозвать сессию. True — была действующая и теперь отозвана (и в БД, и в кэше). + False — сессии нет/уже отозвана. CacheUnavailable — Redis не ответил: + транзакция откатана, сессия осталась действующей, logout не подтверждён.""" + th = token_hash(token) + async with pool.connection() as conn: + async with conn.transaction(): + cur = await conn.execute( + "UPDATE sessions SET revoked_at = now() " + "WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now() " + "RETURNING 1", (th,)) + if await cur.fetchone() is None: + return False + # Внутри транзакции: ошибка Redis → исключение → ROLLBACK отзыва. + await _cache_delete_strict(th) + return True diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..50235cbc --- /dev/null +++ b/compose.yaml @@ -0,0 +1,134 @@ +# Стенд lab3: клиент → lb (HAProxy) → api × 2 → общие PostgreSQL и Redis. +# Запуск: docker compose --env-file .env up -d --build +# Публичный только lb (127.0.0.1:8080); реплики API наружу не публикуются. +name: mtusi-lab3 + +x-api-env: &api-env + DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB} + CACHE_URL: redis://redis:6379/0 + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + DB_POOL_MAX: ${DB_POOL_MAX:-10} + DB_POOL_TIMEOUT: ${DB_POOL_TIMEOUT:-3} + DB_STATEMENT_TIMEOUT_MS: ${DB_STATEMENT_TIMEOUT_MS:-5000} + REDIS_TIMEOUT: ${REDIS_TIMEOUT:-0.5} + SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10} + LOG_LEVEL: ${LOG_LEVEL:-info} + # Миграции выполняет отдельный сервис migrate, а не каждая реплика. + MIGRATE_ON_START: "false" + +services: + postgres: + image: postgres:16.4-alpine + environment: + POSTGRES_DB: ${POSTGRES_DB} + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 5s + timeout: 3s + retries: 20 + deploy: + resources: + limits: {cpus: "1.0", memory: 512M} + restart: unless-stopped + + redis: + image: redis:7.4.1-alpine + # Только кэш сессий: источник истины — PostgreSQL, persistence не нужен. + command: ["redis-server", "--save", "", "--appendonly", "no", + "--maxmemory", "64mb", "--maxmemory-policy", "allkeys-lru"] + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 20 + deploy: + resources: + limits: {cpus: "0.25", memory: 96M} + restart: unless-stopped + + # Однократные миграции до старта реплик (advisory lock защищает и от повтора). + migrate: + build: . + image: mtusi-messenger:lab3 + command: ["python", "-m", "app.migrate"] + environment: *api-env + depends_on: + postgres: + condition: service_healthy + deploy: + resources: + limits: {cpus: "0.5", memory: 256M} + restart: "no" + + api: + build: . + image: mtusi-messenger:lab3 + environment: *api-env + # Портов наружу нет: доступ только через lb. container_name не задан — сервис масштабируется. + expose: ["8080"] + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: {cpus: "0.5", memory: 256M} + healthcheck: + test: ["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)"] + interval: 5s + timeout: 3s + retries: 3 + start_period: 5s + # docker stop → SIGTERM: uvicorn перестаёт принимать соединения и дожидается текущих запросов. + stop_grace_period: 15s + depends_on: + migrate: + condition: service_completed_successfully + postgres: + condition: service_healthy + redis: + condition: service_started + restart: unless-stopped + + lb: + image: haproxy:3.0.5-alpine + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + ports: + - "127.0.0.1:8080:8080" + - "127.0.0.1:8081:8081" + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/healthz"] + interval: 5s + timeout: 3s + retries: 3 + deploy: + resources: + limits: {cpus: "0.5", memory: 128M} + depends_on: + api: + condition: service_started + restart: unless-stopped + + # API с коротким сроком сессии — только для теста истечения (профиль ttl). + # Доступен тоже только через lb: http://localhost:8081 + api-ttl: + image: mtusi-messenger:lab3 + pull_policy: never # образ собирается локально сервисом api + environment: + <<: *api-env + SESSION_TTL_SECONDS: "2" + expose: ["8080"] + deploy: + resources: + limits: {cpus: "0.25", memory: 192M} + depends_on: + postgres: + condition: service_healthy + profiles: ["ttl"] + +volumes: + pgdata: diff --git a/evidence/expiry.txt b/evidence/expiry.txt new file mode 100644 index 00000000..be1991bf --- /dev/null +++ b/evidence/expiry.txt @@ -0,0 +1,13 @@ + Container mtusi-lab3-postgres-1 Running + Container mtusi-lab3-postgres-1 Waiting + Container mtusi-lab3-postgres-1 Healthy + Container mtusi-lab3-api-ttl-1 Starting + Container mtusi-lab3-api-ttl-1 Started + ok - login -> 201 + ok - expires_at is about 2s ahead (got 1.99s) + ok - token works before expiry + ok - expired token -> 401 (cache does not extend the session) + +4 passed, 0 failed + Container mtusi-lab3-api-ttl-1 Stopping + Container mtusi-lab3-api-ttl-1 Stopped diff --git a/evidence/failover-each.json b/evidence/failover-each.json new file mode 100644 index 00000000..3a8427c7 --- /dev/null +++ b/evidence/failover-each.json @@ -0,0 +1,59 @@ +{ + "workload": "4 closed-loop writers, retry same key on failure, 4s before + 12s after stop", + "replicas": [ + { + "stopped_instance": "b5c5b15326cd", + "stop_command_seconds": 1.99, + "before": { + "successful": 502, + "errors": 0, + "successful_rps": 125.4 + }, + "first_10s_after_stop": { + "successful": 990, + "errors": 1, + "successful_rps": 99.0 + }, + "first_success_after_stop_s": 0.001, + "max_gap_without_success_after_stop_s": 0.175, + "stopped_instance_served_after_3s": 0, + "instances_after_stop": [ + "c2fc366c1f6b" + ], + "history_messages": 2035, + "confirmed": 2035, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 1, + "rejoin_seconds": 3.7, + "rejoin_including_start_s": 4.03 + }, + { + "stopped_instance": "c2fc366c1f6b", + "stop_command_seconds": 0.99, + "before": { + "successful": 621, + "errors": 0, + "successful_rps": 155.2 + }, + "first_10s_after_stop": { + "successful": 915, + "errors": 1, + "successful_rps": 91.5 + }, + "first_success_after_stop_s": 0.002, + "max_gap_without_success_after_stop_s": 0.475, + "stopped_instance_served_after_3s": 0, + "instances_after_stop": [ + "b5c5b15326cd" + ], + "history_messages": 1698, + "confirmed": 1698, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 1, + "rejoin_seconds": 3.83, + "rejoin_including_start_s": 4.18 + } + ] +} \ No newline at end of file diff --git a/evidence/failover-each.txt b/evidence/failover-each.txt new file mode 100644 index 00000000..34b16ae5 --- /dev/null +++ b/evidence/failover-each.txt @@ -0,0 +1,71 @@ + ok - at least 2 API replicas running (2) +== Ёхяышър b5c5b15326cd == + ok - LB serves b5c5b15326cd before the test +{ + "stopped_instance": "b5c5b15326cd", + "stop_command_seconds": 1.99, + "before": { + "successful": 502, + "errors": 0, + "successful_rps": 125.4 + }, + "first_10s_after_stop": { + "successful": 990, + "errors": 1, + "successful_rps": 99.0 + }, + "first_success_after_stop_s": 0.001, + "max_gap_without_success_after_stop_s": 0.175, + "stopped_instance_served_after_3s": 0, + "instances_after_stop": [ + "c2fc366c1f6b" + ], + "history_messages": 2035, + "confirmed": 2035, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 1, + "rejoin_seconds": 3.7, + "rejoin_including_start_s": 4.03 +} + ok - writes resumed within 10 s after stopping b5c5b15326cd + ok - stopped b5c5b15326cd not served after detection + ok - confirmed messages preserved + ok - no duplicates despite retries with the same key + ok - b5c5b15326cd rejoined the LB after restart +== Ёхяышър c2fc366c1f6b == + ok - LB serves c2fc366c1f6b before the test +{ + "stopped_instance": "c2fc366c1f6b", + "stop_command_seconds": 0.99, + "before": { + "successful": 621, + "errors": 0, + "successful_rps": 155.2 + }, + "first_10s_after_stop": { + "successful": 915, + "errors": 1, + "successful_rps": 91.5 + }, + "first_success_after_stop_s": 0.002, + "max_gap_without_success_after_stop_s": 0.475, + "stopped_instance_served_after_3s": 0, + "instances_after_stop": [ + "b5c5b15326cd" + ], + "history_messages": 1698, + "confirmed": 1698, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 1, + "rejoin_seconds": 3.83, + "rejoin_including_start_s": 4.18 +} + ok - writes resumed within 10 s after stopping c2fc366c1f6b + ok - stopped c2fc366c1f6b not served after detection + ok - confirmed messages preserved + ok - no duplicates despite retries with the same key + ok - c2fc366c1f6b rejoined the LB after restart + +13 passed, 0 failed diff --git a/evidence/failover-kill9.json b/evidence/failover-kill9.json new file mode 100644 index 00000000..9eee7e9c --- /dev/null +++ b/evidence/failover-kill9.json @@ -0,0 +1,59 @@ +{ + "workload": "4 closed-loop writers, retry same key on failure, 4s before + 12s after stop", + "replicas": [ + { + "stopped_instance": "api-a", + "stop_command_seconds": 0.05, + "before": { + "successful": 1539, + "errors": 0, + "successful_rps": 384.4 + }, + "first_10s_after_stop": { + "successful": 3427, + "errors": 3, + "successful_rps": 342.7 + }, + "first_success_after_stop_s": 0.001, + "max_gap_without_success_after_stop_s": 0.068, + "stopped_instance_served_after_3s": 0, + "instances_after_stop": [ + "api-b" + ], + "history_messages": 5659, + "confirmed": 5659, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 3, + "rejoin_seconds": 2.59, + "rejoin_including_start_s": 2.6 + }, + { + "stopped_instance": "api-b", + "stop_command_seconds": 0.05, + "before": { + "successful": 1518, + "errors": 0, + "successful_rps": 379.2 + }, + "first_10s_after_stop": { + "successful": 3256, + "errors": 3, + "successful_rps": 325.6 + }, + "first_success_after_stop_s": 0.001, + "max_gap_without_success_after_stop_s": 0.052, + "stopped_instance_served_after_3s": 0, + "instances_after_stop": [ + "api-a" + ], + "history_messages": 5534, + "confirmed": 5534, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 3, + "rejoin_seconds": 2.09, + "rejoin_including_start_s": 2.09 + } + ] +} \ No newline at end of file diff --git a/evidence/failover-kill9.txt b/evidence/failover-kill9.txt new file mode 100644 index 00000000..6db04423 --- /dev/null +++ b/evidence/failover-kill9.txt @@ -0,0 +1,71 @@ + ok - at least 2 API replicas running (2) +== реплика api-a == + ok - LB serves api-a before the test +{ + "stopped_instance": "api-a", + "stop_command_seconds": 0.05, + "before": { + "successful": 1539, + "errors": 0, + "successful_rps": 384.4 + }, + "first_10s_after_stop": { + "successful": 3427, + "errors": 3, + "successful_rps": 342.7 + }, + "first_success_after_stop_s": 0.001, + "max_gap_without_success_after_stop_s": 0.068, + "stopped_instance_served_after_3s": 0, + "instances_after_stop": [ + "api-b" + ], + "history_messages": 5659, + "confirmed": 5659, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 3, + "rejoin_seconds": 2.59, + "rejoin_including_start_s": 2.6 +} + ok - writes resumed within 10 s after stopping api-a + ok - stopped api-a not served after detection + ok - confirmed messages preserved + ok - no duplicates despite retries with the same key + ok - api-a rejoined the LB after restart +== реплика api-b == + ok - LB serves api-b before the test +{ + "stopped_instance": "api-b", + "stop_command_seconds": 0.05, + "before": { + "successful": 1518, + "errors": 0, + "successful_rps": 379.2 + }, + "first_10s_after_stop": { + "successful": 3256, + "errors": 3, + "successful_rps": 325.6 + }, + "first_success_after_stop_s": 0.001, + "max_gap_without_success_after_stop_s": 0.052, + "stopped_instance_served_after_3s": 0, + "instances_after_stop": [ + "api-a" + ], + "history_messages": 5534, + "confirmed": 5534, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 3, + "rejoin_seconds": 2.09, + "rejoin_including_start_s": 2.09 +} + ok - writes resumed within 10 s after stopping api-b + ok - stopped api-b not served after detection + ok - confirmed messages preserved + ok - no duplicates despite retries with the same key + ok - api-b rejoined the LB after restart + +13 passed, 0 failed diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 00000000..22d45cc5 --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,32 @@ +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 108, "failed_attempts": 0, "first_recovery_seconds": 1.751} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab3-api-5 mtusi-messenger:lab3 "python -m app" api 8 minutes ago Up 8 minutes (healthy) 8080/tcp +mtusi-lab3-api-6 mtusi-messenger:lab3 "python -m app" api 8 minutes ago Exited (0) 14 seconds ago + Container mtusi-lab3-postgres-1 Waiting + Container mtusi-lab3-postgres-1 Healthy + Container mtusi-lab3-migrate-1 Starting + Container mtusi-lab3-migrate-1 Started + Container mtusi-lab3-migrate-1 Waiting + Container mtusi-lab3-postgres-1 Waiting + Container mtusi-lab3-postgres-1 Healthy + Container mtusi-lab3-migrate-1 Exited + Container mtusi-lab3-api-6 Starting + Container mtusi-lab3-api-6 Started +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 106, "failed_attempts": 0, "first_recovery_seconds": 1.862} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab3-api-5 mtusi-messenger:lab3 "python -m app" api 9 minutes ago Up 9 minutes (healthy) 8080/tcp +mtusi-lab3-api-6 mtusi-messenger:lab3 "python -m app" api 9 minutes ago Exited (0) 14 seconds ago + Container mtusi-lab3-postgres-1 Waiting + Container mtusi-lab3-postgres-1 Healthy + Container mtusi-lab3-migrate-1 Starting + Container mtusi-lab3-migrate-1 Started + Container mtusi-lab3-migrate-1 Waiting + Container mtusi-lab3-postgres-1 Waiting + Container mtusi-lab3-postgres-1 Healthy + Container mtusi-lab3-migrate-1 Exited + Container mtusi-lab3-api-6 Starting + Container mtusi-lab3-api-6 Started diff --git a/evidence/idempotency.txt b/evidence/idempotency.txt new file mode 100644 index 00000000..cc0852f4 --- /dev/null +++ b/evidence/idempotency.txt @@ -0,0 +1,21 @@ +== 20 ярЁрыыхы№э√ї чряЁюёют ё юфэшь ъы■ўюь == + ok - all parallel repeats -> 201 (got [201]) + ok - all responses carry the same message id (1 distinct) + ok - requests were served by >=2 replicas (2) + ok - exactly one message in history + ok - every replay returns the identical Message +== ёхьрэЄшър ъы■ўр == + ok - same key, different body -> 409 (got 409) + ok - other JSON formatting = same request (got 201) + ok - same key in another chat is independent + ok - same key from another user is independent + ok - missing Idempotency-Key -> 400 (got 400) + ok - invalid key 'has space'... -> 400 (got 400) + ok - invalid key 'xxxxxxxxxxxx'... -> 400 (got 400) + ok - invalid key 'slash/key'... -> 400 (got 400) + ok - replay without session -> 401, access re-checked (got 401) +== эхюяЁхфхы╕ээ√щ Ёхчєы№ЄрЄ: ъышхэЄ яютЄюЁ хЄ ё Єхь цх ъы■ўюь == + ok - retry after uncertain result -> 201 + ok - still exactly one message + +16 passed, 0 failed diff --git a/evidence/load.json b/evidence/load.json new file mode 100644 index 00000000..966c4897 --- /dev/null +++ b/evidence/load.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 24.987, + "concurrency": 4, + "successful_requests": 2511, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 100.493, + "successful_latency_ms": { + "p50": 14.321, + "p95": 83.278, + "p99": 169.497 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/load.txt b/evidence/load.txt new file mode 100644 index 00000000..d26d9e5a --- /dev/null +++ b/evidence/load.txt @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 24.987, + "concurrency": 4, + "successful_requests": 2511, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 100.493, + "successful_latency_ms": { + "p50": 14.321, + "p95": 83.278, + "p99": 169.497 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/logout-cache.txt b/evidence/logout-cache.txt new file mode 100644 index 00000000..2f91ee5c --- /dev/null +++ b/evidence/logout-cache.txt @@ -0,0 +1,20 @@ +python : Container mtusi-lab3-redis-1 Paused +строка:1 знак:23 ++ ... cache.txt { python student-tests\logout_cache.py --base-url http://lo ... ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : NotSpecified: ( Container mtusi-lab3-redis-1 Paused :String) [], RemoteException + + FullyQualifiedErrorId : NativeCommandError + + Container mtusi-lab3-redis-1 Unpaused + ok - session is warmed up in cache +== Redis яЁшюёЄрэютыхэ == + $ docker compose --env-file .env pause redis + ok - logout is NOT confirmed while cache cannot be invalidated (got 503, expected 503) + $ docker compose --env-file .env unpause redis +== Redis тюёёЄрэютыхэ == + ok - unconfirmed logout left the session consistent and valid (got 200) + ok - retry logout after Redis recovery -> 204 (got 204) + ok - old token after confirmed logout -> 401, no stale cache copy (got 401) + ok - old token still rejected on repeat (got 401) + +6 passed, 0 failed diff --git a/evidence/migrations.txt b/evidence/migrations.txt new file mode 100644 index 00000000..ba33f285 --- /dev/null +++ b/evidence/migrations.txt @@ -0,0 +1,9 @@ +migrate-1 | applied: nothing (up to date) +migrate-1 | applied: nothing (up to date) +migrate-1 | applied: nothing (up to date) + version | applied_at +------------------+------------------------------- + 0001_init | 2026-10-22 14:56:14.127864+00 + 0002_idempotency | 2026-10-22 14:56:14.257126+00 +(2 rows) + diff --git a/evidence/outage.txt b/evidence/outage.txt new file mode 100644 index 00000000..c633f070 --- /dev/null +++ b/evidence/outage.txt @@ -0,0 +1,28 @@ + Container mtusi-lab3-redis-1 Stopping + Container mtusi-lab3-redis-1 Stopped + Container mtusi-lab3-redis-1 Starting + Container mtusi-lab3-redis-1 Started + Container mtusi-lab3-postgres-1 Stopping + Container mtusi-lab3-postgres-1 Stopped + Container mtusi-lab3-postgres-1 Starting + Container mtusi-lab3-postgres-1 Started +== 1. Redis недоступен == + $ docker compose --env-file .env stop redis + ok - valid token still works without Redis (cache bypassed) + ok - writes still work without Redis + ok - login works without Redis + ok - forged token still rejected without Redis + $ docker compose --env-file .env start redis +== 2. PostgreSQL недоступен == + $ docker compose --env-file .env stop postgres + ok - history without DB -> 503, not a hang (got 503) + ok - unknown token is never trusted without DB (got 503) + ok - anonymous request -> 401 + ok - /health/ready -> 503 + ok - /health/live -> 200 (process is alive) + $ docker compose --env-file .env start postgres +== 3. восстановление == + ok - /health/ready back to 200 + ok - same token reads the same history after DB is back + +11 passed, 0 failed diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..02a68d06 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,14 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab3-api-5 mtusi-messenger:lab3 "python -m app" api 9 minutes ago Up 9 minutes (healthy) 8080/tcp +mtusi-lab3-api-6 mtusi-messenger:lab3 "python -m app" api 9 minutes ago Up 15 seconds (healthy) 8080/tcp +mtusi-lab3-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 12 minutes ago Up 2 minutes (healthy) 127.0.0.1:8080-8081->8080-8081/tcp +mtusi-lab3-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 20 minutes ago Up About a minute (healthy) 5432/tcp +mtusi-lab3-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis 20 minutes ago Up About a minute (healthy) 6379/tcp +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab3-api-5 mtusi-messenger:lab3 "python -m app" api 9 minutes ago Up 3 seconds (health: starting) 8080/tcp +mtusi-lab3-api-6 mtusi-messenger:lab3 "python -m app" api 9 minutes ago Up 4 seconds (health: starting) 8080/tcp +mtusi-lab3-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 12 minutes ago Up 2 seconds (health: starting) 127.0.0.1:8080-8081->8080-8081/tcp +mtusi-lab3-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 20 minutes ago Up 4 seconds (health: starting) 5432/tcp +mtusi-lab3-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 5 seconds (health: starting) 6379/tcp diff --git a/evidence/rollback.txt b/evidence/rollback.txt new file mode 100644 index 00000000..5d284c39 --- /dev/null +++ b/evidence/rollback.txt @@ -0,0 +1,3 @@ + ok - insert of unknown member failed on foreign key + ok - after rollback: chats=0, members=0 (expected 0, 0) +PASS diff --git a/evidence/rolling-update.json b/evidence/rolling-update.json new file mode 100644 index 00000000..6ac6608c --- /dev/null +++ b/evidence/rolling-update.json @@ -0,0 +1,53 @@ +{ + "replicas_before": [ + "b5c5b15326cd", + "c2fc366c1f6b" + ], + "replicas_after": [ + "751a5997c6bc", + "dc76a00e8ff8" + ], + "all_on_new_image": true, + "steps": [ + { + "old": "b5c5b15326cd", + "new": "dc76a00e8ff8", + "new_healthy": true, + "new_served_by_lb": true, + "old_stop_seconds": 1.29 + }, + { + "old": "c2fc366c1f6b", + "new": "751a5997c6bc", + "new_healthy": true, + "new_served_by_lb": true, + "old_stop_seconds": 1.36 + } + ], + "update_duration_s": 18.6, + "before_update": { + "successful": 475, + "errors": 0, + "successful_rps": 158.2 + }, + "during_update": { + "successful": 2634, + "errors": 0, + "successful_rps": 141.5 + }, + "after_update": { + "successful": 507, + "errors": 0, + "successful_rps": 169.0 + }, + "max_gap_without_success_s": 0.469, + "instances_serving_at_end": [ + "751a5997c6bc", + "dc76a00e8ff8" + ], + "history_messages": 3620, + "confirmed": 3620, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 0 +} \ No newline at end of file diff --git a/evidence/rolling-update.txt b/evidence/rolling-update.txt new file mode 100644 index 00000000..5d453e2b --- /dev/null +++ b/evidence/rolling-update.txt @@ -0,0 +1,97 @@ + $ docker compose --env-file .env build api + $ docker compose --env-file .env run --rm migrate + $ docker image inspect -f {{.Id}} mtusi-messenger:lab3 + $ docker compose --env-file .env ps -q api + ok - 2 replicas before update + $ docker inspect -f {{.Image}} b5c5b15326cda7faec130cd40e44c64bc75fab16d4822d19c77e293d61e90556 + $ docker inspect -f {{.Image}} c2fc366c1f6bd4375d56f4cacc53ccc56acf6bc744c8450718cf448035bdb435 + $ docker compose --env-file .env ps -q api + $ docker compose --env-file .env up -d --no-deps --no-recreate --scale api=3 api + $ docker compose --env-file .env ps -q api + ok - one new replica started for b5c5b15326cd + $ docker inspect -f {{.State.Health.Status}} dc76a00e8ff80eeb393286be367dc2e42aa1f2c55314739b12c77902a52a08a7 + $ docker inspect -f {{.State.Health.Status}} dc76a00e8ff80eeb393286be367dc2e42aa1f2c55314739b12c77902a52a08a7 + $ docker inspect -f {{.State.Health.Status}} dc76a00e8ff80eeb393286be367dc2e42aa1f2c55314739b12c77902a52a08a7 + $ docker inspect -f {{.State.Health.Status}} dc76a00e8ff80eeb393286be367dc2e42aa1f2c55314739b12c77902a52a08a7 + $ docker inspect -f {{.State.Health.Status}} dc76a00e8ff80eeb393286be367dc2e42aa1f2c55314739b12c77902a52a08a7 + $ docker inspect -f {{.State.Health.Status}} dc76a00e8ff80eeb393286be367dc2e42aa1f2c55314739b12c77902a52a08a7 + $ docker inspect -f {{.State.Health.Status}} dc76a00e8ff80eeb393286be367dc2e42aa1f2c55314739b12c77902a52a08a7 + $ docker stop -t 15 b5c5b15326cda7faec130cd40e44c64bc75fab16d4822d19c77e293d61e90556 + $ docker rm b5c5b15326cda7faec130cd40e44c64bc75fab16d4822d19c77e293d61e90556 + ok - new replica dc76a00e8ff8 healthy and in LB before old b5c5b15326cd stops + $ docker compose --env-file .env ps -q api + $ docker compose --env-file .env up -d --no-deps --no-recreate --scale api=3 api + $ docker compose --env-file .env ps -q api + ok - one new replica started for c2fc366c1f6b + $ docker inspect -f {{.State.Health.Status}} 751a5997c6bc08109eb9a7b18c734172b958053acb542f3df1bec0674c4ad534 + $ docker inspect -f {{.State.Health.Status}} 751a5997c6bc08109eb9a7b18c734172b958053acb542f3df1bec0674c4ad534 + $ docker inspect -f {{.State.Health.Status}} 751a5997c6bc08109eb9a7b18c734172b958053acb542f3df1bec0674c4ad534 + $ docker inspect -f {{.State.Health.Status}} 751a5997c6bc08109eb9a7b18c734172b958053acb542f3df1bec0674c4ad534 + $ docker inspect -f {{.State.Health.Status}} 751a5997c6bc08109eb9a7b18c734172b958053acb542f3df1bec0674c4ad534 + $ docker inspect -f {{.State.Health.Status}} 751a5997c6bc08109eb9a7b18c734172b958053acb542f3df1bec0674c4ad534 + $ docker inspect -f {{.State.Health.Status}} 751a5997c6bc08109eb9a7b18c734172b958053acb542f3df1bec0674c4ad534 + $ docker stop -t 15 c2fc366c1f6bd4375d56f4cacc53ccc56acf6bc744c8450718cf448035bdb435 + $ docker rm c2fc366c1f6bd4375d56f4cacc53ccc56acf6bc744c8450718cf448035bdb435 + ok - new replica 751a5997c6bc healthy and in LB before old c2fc366c1f6b stops + $ docker compose --env-file .env ps -q api + $ docker inspect -f {{.Image}} dc76a00e8ff80eeb393286be367dc2e42aa1f2c55314739b12c77902a52a08a7 + $ docker inspect -f {{.Image}} 751a5997c6bc08109eb9a7b18c734172b958053acb542f3df1bec0674c4ad534 +{ + "replicas_before": [ + "b5c5b15326cd", + "c2fc366c1f6b" + ], + "replicas_after": [ + "751a5997c6bc", + "dc76a00e8ff8" + ], + "all_on_new_image": true, + "steps": [ + { + "old": "b5c5b15326cd", + "new": "dc76a00e8ff8", + "new_healthy": true, + "new_served_by_lb": true, + "old_stop_seconds": 1.29 + }, + { + "old": "c2fc366c1f6b", + "new": "751a5997c6bc", + "new_healthy": true, + "new_served_by_lb": true, + "old_stop_seconds": 1.36 + } + ], + "update_duration_s": 18.6, + "before_update": { + "successful": 475, + "errors": 0, + "successful_rps": 158.2 + }, + "during_update": { + "successful": 2634, + "errors": 0, + "successful_rps": 141.5 + }, + "after_update": { + "successful": 507, + "errors": 0, + "successful_rps": 169.0 + }, + "max_gap_without_success_s": 0.469, + "instances_serving_at_end": [ + "751a5997c6bc", + "dc76a00e8ff8" + ], + "history_messages": 3620, + "confirmed": 3620, + "lost_or_changed": 0, + "duplicate_texts": 0, + "retries_with_same_key": 0 +} + ok - replica count restored to 2 + ok - all replicas run the new image + ok - old replicas no longer serve traffic + ok - no lost or duplicated writes + +9 passed, 0 failed diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..99b663aa --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,2 @@ +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +PASS: lab3 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt new file mode 100644 index 00000000..7e57d9f9 --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1,83 @@ +== рєЄхэЄшЇшърЎш  == + ok - wrong password -> 401 + Basic challenge + ok - unknown user -> 401 (same as wrong password) + ok - no token -> 401 + Bearer challenge + ok - X-User-Id alone gives no access + ok - unknown/forged token -> 401 + ok - Basic on business endpoint -> 401 + ok - X-User-Id cannot override bearer identity + ok - password shorter than 12 -> 400 +== logout == + ok - logout -> 204 + ok - token after logout -> 401 + ok - second logout -> 401 +== уюэър ЁхушёЄЁрЎшш юфэюую username == +python : Traceback (most recent call last): +строка:1 знак:24 ++ ... tests.txt { python student-tests\run.py --base-url http://localhost:8 ... ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : NotSpecified: (Traceback (most recent call last)::String) [], RemoteException + + FullyQualifiedErrorId : NativeCommandError + + File "C:\Users\79152\Desktop\mtusi2026lab3\student-tests\run.py", line 122, in + main() + ~~~~^^ + File "C:\Users\79152\Desktop\mtusi2026lab3\student-tests\run.py", line 67, in main + codes = list(pool.map(reg, range(20))) + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\concurrent\futures\_base.py", line 639, in +result_iterator + yield _result_or_cancel(fs.pop()) + ~~~~~~~~~~~~~~~~~^^^^^^^^^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\concurrent\futures\_base.py", line 311, in +_result_or_cancel + return fut.result(timeout) + ~~~~~~~~~~^^^^^^^^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\concurrent\futures\_base.py", line 450, in result + return self.__get_result() + ~~~~~~~~~~~~~~~~~^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\concurrent\futures\_base.py", line 395, in +__get_result + raise self._exception + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\concurrent\futures\thread.py", line 86, in run + result = ctx.run(self.task) + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\concurrent\futures\thread.py", line 73, in run + return fn(*args, **kwargs) + File "C:\Users\79152\Desktop\mtusi2026lab3\student-tests\run.py", line 63, in reg + st, _, _ = api.call("POST", "/api/v1/users", {"username": name, "display_name": "r", "password": PASSWORD}) + ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\79152\Desktop\mtusi2026lab3\student-tests\common.py", line 34, in call + st, raw, rh = self.raw(method, path, data, h, timeout=timeout) + ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\79152\Desktop\mtusi2026lab3\student-tests\common.py", line 18, in raw + with urllib.request.urlopen(req, timeout=timeout) as r: + ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\urllib\request.py", line 187, in urlopen + return opener.open(url, data, timeout) + ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\urllib\request.py", line 487, in open + response = self._open(req, data) + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\urllib\request.py", line 504, in _open + result = self._call_chain(self.handle_open, protocol, protocol + + '_open', req) + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\urllib\request.py", line 464, in _call_chain + result = func(*args) + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\urllib\request.py", line 1350, in http_open + return self.do_open(http.client.HTTPConnection, req) + ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\urllib\request.py", line 1325, in do_open + r = h.getresponse() + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\http\client.py", line 1450, in getresponse + response.begin() + ~~~~~~~~~~~~~~^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\http\client.py", line 336, in begin + version, status, reason = self._read_status() + ~~~~~~~~~~~~~~~~~^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\http\client.py", line 297, in _read_status + line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") + ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ + File "C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\Lib\socket.py", line 725, in readinto + return self._sock.recv_into(b) + ~~~~~~~~~~~~~~~~~~~~^^^ +TimeoutError: timed out +sent=100 accepted=100 received=100 unique_ids=100 all_texts_present=True +PASS diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 00000000..1e7c93f4 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,72 @@ +# Балансировщик lab3: единственная публичная точка входа (127.0.0.1:8080). +# Реплики API находятся через DNS Docker по имени сервиса "api" +# (server-template + resolvers): добавление/удаление контейнеров подхватывается +# без перезапуска LB. Активная проверка /health/ready исключает недоступную реплику. +global + log stdout format raw local0 info + maxconn 2048 + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + hold other 5s + hold refused 5s + hold nx 5s + hold timeout 5s + hold obsolete 5s + accepted_payload_size 8192 + +defaults + mode http + log global + option httplog + # Короткий connect: остановленный контейнер не отвечает на SYN, и без этого + # запрос ждал бы 2 c до повтора на другой реплике. + timeout connect 500ms + timeout client 30s + timeout server 15s + timeout http-request 10s + # Повтор только при ошибке УСТАНОВКИ соединения (запрос ещё не отправлен) — + # безопасно даже для POST; redispatch отправляет повтор на другую реплику. + retries 3 + option redispatch + +frontend fe_api + bind :8080 + default_backend api + +# Отдельный вход для теста истечения сессии (профиль ttl): тоже только через LB. +frontend fe_api_ttl + bind :8081 + default_backend api_ttl + +# Проверка живости самого LB для healthcheck контейнера. +frontend fe_health + bind :8404 + monitor-uri /healthz + +backend api + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + # Проверка раз в 0,5 c; 2 неудачи подряд → реплика исключается (≈1–1,5 c), + # 2 успеха подряд → возвращается. + default-server inter 500ms fall 2 rise 2 resolvers docker init-addr none + server-template api 6 api:8080 check + # Запасной путь, только если НИ ОДНА реплика не готова (например, упала общая БД): + # тогда LB всё равно передаёт запрос в живой процесс, и API отвечает по контракту + # (401 анониму, 503 unavailable в формате ошибки, /health/live 200), а не голым 503 LB. + # Остановленный контейнер исчезает из DNS и сюда не попадает. + option allbackups + # allow-dup-ip: те же IP, что у основных серверов (по умолчанию HAProxy не даёт + # одному IP достаться двум серверам бэкенда, и резервные остались бы без адреса). + server-template fallback 6 api:8080 backup resolve-opts allow-dup-ip + +backend api_ttl + option httpchk GET /health/ready + http-check expect status 200 + default-server check inter 500ms fall 2 rise 2 resolvers docker init-addr none + server-template ttl 2 api-ttl:8080 diff --git a/migrations/0001_init.sql b/migrations/0001_init.sql new file mode 100644 index 00000000..229ff8e4 --- /dev/null +++ b/migrations/0001_init.sql @@ -0,0 +1,54 @@ +-- 0001: начальная схема мессенджера (lab2). +-- Источник истины для пользователей, чатов, участников, сообщений и сессий. + +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT users_username_key UNIQUE (username), + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_len CHECK (char_length(display_name) BETWEEN 1 AND 100) +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_by uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL, + CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100) +); + +-- Участники чата. position сохраняет порядок member_ids из запроса. +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id), + position integer NOT NULL, + PRIMARY KEY (chat_id, user_id) +); +-- «Мои чаты»: найти чаты пользователя без полного скана. +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users (id), + text text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000) +); +-- Keyset-пагинация истории: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) +-- ORDER BY created_at, id LIMIT n — индекс отдаёт страницу без скана всей истории. +CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); + +-- Сессии. Храним только SHA-256 от токена: утечка таблицы не даёт рабочих токенов. +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + revoked_at timestamptz +); +CREATE INDEX sessions_user_idx ON sessions (user_id); +CREATE INDEX sessions_expires_idx ON sessions (expires_at); diff --git a/migrations/0002_idempotency.sql b/migrations/0002_idempotency.sql new file mode 100644 index 00000000..9f4bf84f --- /dev/null +++ b/migrations/0002_idempotency.sql @@ -0,0 +1,17 @@ +-- 0002: общая идемпотентность POST /chats/{chat_id}/messages (lab3). +-- Область уникальности ключа: пользователь + чат (метод и путь фиксированы) + ключ. +-- Миграция только добавляет таблицу: старая версия API (lab2) с ней совместима. + +CREATE TABLE idempotency_keys ( + user_id uuid NOT NULL REFERENCES users (id), + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + idem_key text NOT NULL, + request_hash bytea NOT NULL, -- SHA-256 канонического тела запроса + -- Ключ вставляется ДО сообщения в той же транзакции: проверка FK — при COMMIT. + message_id uuid NOT NULL REFERENCES messages (id) DEFERRABLE INITIALLY DEFERRED, + created_at timestamptz NOT NULL, + PRIMARY KEY (user_id, chat_id, idem_key), + CONSTRAINT idempotency_key_format CHECK (idem_key ~ '^[A-Za-z0-9._:-]{1,128}$') +); +-- Для очистки ключей старше IDEMPOTENCY_TTL_SECONDS. +CREATE INDEX idempotency_keys_created_idx ON idempotency_keys (created_at); diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..ea43c0ef --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +# Рантайм-зависимости, версии закреплены для воспроизводимой сборки. +fastapi==0.141.1 +uvicorn[standard]==0.46.0 +pydantic==2.13.3 +psycopg[binary]==3.3.6 +psycopg-pool==3.3.3 +argon2-cffi==25.1.0 +redis==8.1.0 diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..effedd01 --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,4 @@ +@echo off +rem Restart hook (Windows): same as restart.sh, volumes are kept. +cd /d "%~dp0.." +docker compose --env-file .env restart postgres redis api lb diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..93da1aa9 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# Restart hook для make test-persistence: перезапускает ВСЕ реплики API, LB и +# хранилища (PostgreSQL, Redis). Volumes сохраняются; ничего не удаляется и не сидится. +set -eu +cd "$(dirname "$0")/.." +docker compose --env-file .env restart postgres redis api lb diff --git a/scripts/restore-api.cmd b/scripts/restore-api.cmd new file mode 100644 index 00000000..e63eb7a0 --- /dev/null +++ b/scripts/restore-api.cmd @@ -0,0 +1,4 @@ +@echo off +rem Restore stopped api replicas after the failover test. +cd /d "%~dp0.." +docker compose --env-file .env start api diff --git a/scripts/restore-api.sh b/scripts/restore-api.sh new file mode 100644 index 00000000..f5d4a8a5 --- /dev/null +++ b/scripts/restore-api.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# Вернуть остановленные реплики API после failover-теста. +set -eu +cd "$(dirname "$0")/.." +docker compose --env-file .env start api diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..69f73d98 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,7 @@ +@echo off +rem Failover hook (Windows): stop ONE api container whose short ID = TARGET_INSTANCE_ID. +if "%TARGET_INSTANCE_ID%"=="" exit /b 2 +set CID= +for /f %%i in ('docker ps -q --filter "id=%TARGET_INSTANCE_ID%" --filter "label=com.docker.compose.service=api"') do set CID=%%i +if "%CID%"=="" exit /b 1 +docker stop -t 8 %CID% >nul diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..29224717 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Failover hook для make test-failover. +# X-Instance-Id реплики = hostname контейнера = короткий ID контейнера Docker. +# Останавливаем РОВНО этот контейнер, и только если он относится к сервису api +# (БД, Redis и LB этот скрипт не трогает). Реплика остаётся остановленной; +# вернуть её: scripts/restore-api.sh +set -eu +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +cd "$(dirname "$0")/.." +cid=$(docker ps -q --filter "id=${TARGET_INSTANCE_ID}" --filter "label=com.docker.compose.service=api") +[ -n "$cid" ] || { echo "no running api container for ${TARGET_INSTANCE_ID}" >&2; exit 1; } +docker stop -t 8 "$cid" >/dev/null diff --git a/student-tests/common.py b/student-tests/common.py new file mode 100644 index 00000000..1cd2bd7b --- /dev/null +++ b/student-tests/common.py @@ -0,0 +1,75 @@ +"""Общий HTTP-клиент для собственных тестов (только стандартная библиотека).""" +import base64 +import json +import urllib.error +import urllib.request +import uuid + +PASSWORD = "Test-password-" + uuid.uuid4().hex[:8] + + +class Api: + def __init__(self, base: str): + self.base = base.rstrip("/") + + def raw(self, method, path, data=None, headers=None, timeout=10): + req = urllib.request.Request(self.base + path, data=data, headers=headers or {}, method=method) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.status, r.read(), r.headers + except urllib.error.HTTPError as e: + return e.code, e.read(), e.headers + + def call(self, method, path, body=None, token=None, headers=None, timeout=10): + h = dict(headers or {}) + data = None + if body is not None: + data = json.dumps(body, ensure_ascii=False).encode() + h["Content-Type"] = "application/json" + if token: + h["Authorization"] = "Bearer " + token + # С lab3 POST сообщения требует Idempotency-Key; если тест не задал свой — новый ключ. + if method == "POST" and path.split("?")[0].endswith("/messages"): + h.setdefault("Idempotency-Key", uuid.uuid4().hex) + st, raw, rh = self.raw(method, path, data, h, timeout=timeout) + try: + return st, json.loads(raw or b"null"), rh + except ValueError: + return st, None, rh + + def register(self, prefix: str, password: str = PASSWORD) -> dict: + name = (prefix + "_" + uuid.uuid4().hex[:10])[:32] + st, user, _ = self.call("POST", "/api/v1/users", + {"username": name, "display_name": prefix, "password": password}) + assert st == 201, f"register {name}: {st} {user}" + user["password"] = password + return user + + def login(self, username: str, password: str): + cred = base64.b64encode(f"{username}:{password}".encode()).decode() + st, body, rh = self.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}) + return st, body, rh + + def new_user(self, prefix: str) -> dict: + user = self.register(prefix) + st, sess, _ = self.login(user["username"], user["password"]) + assert st == 201, f"login: {st}" + user["token"] = sess["token"] + return user + + +class Report: + def __init__(self): + self.passed = self.failed = 0 + + def check(self, cond, name): + if cond: + self.passed += 1 + print(f" ok - {name}") + else: + self.failed += 1 + print(f" FAIL - {name}") + + def finish(self): + print(f"\n{self.passed} passed, {self.failed} failed") + raise SystemExit(1 if self.failed else 0) diff --git a/student-tests/expiry.py b/student-tests/expiry.py new file mode 100644 index 00000000..503cf37c --- /dev/null +++ b/student-tests/expiry.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +""" +Истечение сессии при коротком SESSION_TTL_SECONDS (=2). +Запускается против отдельного экземпляра API с коротким TTL: + docker compose --env-file .env --profile ttl up -d api-ttl + python student-tests/expiry.py --base-url http://localhost:8081 +""" +import argparse +import time +from datetime import datetime, timezone + +from common import Api, Report + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8081") + ap.add_argument("--ttl", type=float, default=2) + args = ap.parse_args() + api, r = Api(args.base_url), Report() + # Экземпляр с коротким TTL мог только что стартовать: ждём готовности до 60 с. + deadline = time.time() + 60 + while True: + try: + if api.raw("GET", "/health/ready", timeout=2)[0] == 200: + break + except OSError: + pass + if time.time() > deadline: + raise SystemExit("API is not ready at " + args.base_url) + time.sleep(1) + + user = api.register("ttl") + st, sess, _ = api.login(user["username"], user["password"]) + r.check(st == 201, "login -> 201") + exp = datetime.fromisoformat(sess["expires_at"].replace("Z", "+00:00")) + left = (exp - datetime.now(timezone.utc)).total_seconds() + r.check(0 < left <= args.ttl + 1, f"expires_at is about {args.ttl}s ahead (got {left:.2f}s)") + st, _, _ = api.call("GET", "/api/v1/users/me", token=sess["token"]) + r.check(st == 200, "token works before expiry") # заодно кладёт сессию в кэш Redis + time.sleep(args.ttl + 1.5) + st, _, rh = api.call("GET", "/api/v1/users/me", token=sess["token"]) + r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Bearer"), + "expired token -> 401 (cache does not extend the session)") + r.finish() + + +if __name__ == "__main__": + main() diff --git a/student-tests/explain.sql b/student-tests/explain.sql new file mode 100644 index 00000000..235f1f9a --- /dev/null +++ b/student-tests/explain.sql @@ -0,0 +1,60 @@ +-- План запроса истории на ≥10 000 сообщениях (уровень «4»). +-- Всё внутри транзакции с ROLLBACK: учебные данные не остаются в базе. +-- Запуск (одинаково в PowerShell и sh): +-- docker compose cp student-tests/explain.sql postgres:/tmp/explain.sql +-- docker compose exec postgres psql -U messenger -d messenger -f /tmp/explain.sql +BEGIN; + +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES ('00000000-0000-4000-8000-000000000001', 'explain_seed', 'Seed', 'x', now()); + +-- Чат, историю которого читаем, и 9 «соседних» чатов, чтобы в таблице были чужие сообщения. +INSERT INTO chats (id, title, created_by, created_at) +SELECT ('00000000-0000-4000-8000-0000000001' || lpad(g::text, 2, '0'))::uuid, 'seed ' || g, + '00000000-0000-4000-8000-000000000001', now() +FROM generate_series(0, 9) g; + +INSERT INTO chat_members (chat_id, user_id, position) +SELECT ('00000000-0000-4000-8000-0000000001' || lpad(g::text, 2, '0'))::uuid, + '00000000-0000-4000-8000-000000000001', 0 +FROM generate_series(0, 9) g; + +-- 12 000 сообщений в целевом чате + 48 000 в соседних = 60 000 строк. +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), + ('00000000-0000-4000-8000-0000000001' || lpad((CASE WHEN g <= 12000 THEN 0 ELSE g % 9 + 1 END)::text, 2, '0'))::uuid, + '00000000-0000-4000-8000-000000000001', + 'msg ' || g, + now() - interval '1 day' + g * interval '1 millisecond' +FROM generate_series(1, 60000) g; + +ANALYZE messages; + +SELECT count(*) AS messages_in_target_chat +FROM messages WHERE chat_id = '00000000-0000-4000-8000-000000000100'; + +\echo '=== 1. Первая страница (limit 50 + 1) ===' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = '00000000-0000-4000-8000-000000000100' +ORDER BY created_at, id LIMIT 51; + +\echo '=== 2. Страница из середины истории (keyset-курсор после ~6000-го сообщения) ===' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = '00000000-0000-4000-8000-000000000100' + AND (created_at, id) > (now() - interval '1 day' + 6000 * interval '1 millisecond', + '00000000-0000-0000-0000-000000000000') +ORDER BY created_at, id LIMIT 51; + +\echo '=== 3. Для сравнения: та же страница, если запретить индекс ===' +SET LOCAL enable_indexscan = off; +SET LOCAL enable_bitmapscan = off; +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = '00000000-0000-4000-8000-000000000100' + AND (created_at, id) > (now() - interval '1 day' + 6000 * interval '1 millisecond', + '00000000-0000-0000-0000-000000000000') +ORDER BY created_at, id LIMIT 51; + +ROLLBACK; diff --git a/student-tests/failover_each.py b/student-tests/failover_each.py new file mode 100644 index 00000000..2bd2894c --- /dev/null +++ b/student-tests/failover_each.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +""" +Поочерёдная остановка КАЖДОЙ реплики API под нагрузкой (lab3, уровень «4»). + +Для каждой реплики: дождаться, что LB обслуживает все реплики → запустить +нагрузку записи → через --before секунд остановить реплику (docker stop, SIGTERM) +→ ещё --after секунд нагрузки → собрать RPS, ошибки, время восстановления → +проверить сохранность и отсутствие дублей → вернуть реплику и дождаться, +что LB снова её обслуживает. + + python student-tests/failover_each.py --base-url http://localhost:8080 --output evidence/failover-each.json +""" +import argparse +import json +import shlex +import subprocess +import time + +from common import Api, Report +from loadgen import LoadGen + +COMPOSE = "docker compose --env-file .env" + + +def run(cmd: str, **fmt) -> str: + out = subprocess.run(shlex.split(cmd.format(**fmt)), check=True, capture_output=True, text=True) + return out.stdout + + +def served_instances(api: Api, n: int = 30) -> set: + seen = set() + for _ in range(n): + try: + st, _, rh = api.call("GET", "/health/live", timeout=2) + if st == 200: + seen.add(rh.get("X-Instance-Id", "")) + except OSError: + pass + return seen + + +def wait_served(api: Api, iid: str, seconds: float = 60) -> float: + start = time.monotonic() + while time.monotonic() - start < seconds: + if iid in served_instances(api, 10): + return round(time.monotonic() - start, 2) + time.sleep(0.5) + return -1 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8080") + ap.add_argument("--workers", type=int, default=4) + ap.add_argument("--before", type=float, default=4, help="секунд нагрузки до остановки") + ap.add_argument("--after", type=float, default=12, help="секунд нагрузки после остановки") + ap.add_argument("--list-cmd", default=f"{COMPOSE} ps -q api") + ap.add_argument("--stop-cmd", default="docker stop -t 8 {id}") + ap.add_argument("--start-cmd", default="docker start {id}") + ap.add_argument("--output", default=None) + args = ap.parse_args() + api, r = Api(args.base_url), Report() + + replicas = [line.strip() for line in run(args.list_cmd).splitlines() if line.strip()] + r.check(len(replicas) >= 2, f"at least 2 API replicas running ({len(replicas)})") + results = [] + user = api.new_user("failover") + for cid in replicas: + iid = cid[:12] # X-Instance-Id = hostname контейнера = короткий ID + print(f"== реплика {iid} ==") + r.check(wait_served(api, iid) >= 0, f"LB serves {iid} before the test") + st, chat, _ = api.call("POST", "/api/v1/chats", {"title": f"failover {iid}", "member_ids": [user["id"]]}, + token=user["token"]) + gen = LoadGen(api, user["token"], chat["id"], workers=args.workers) + gen.start() + time.sleep(args.before) + t_stop = time.monotonic() + run(args.stop_cmd, id=cid) + stop_cmd_seconds = round(time.monotonic() - t_stop, 2) + time.sleep(args.after) + gen.stop() + rel = t_stop - gen.t0 + later = gen.instances_after(t_stop + 3) + res = { + "stopped_instance": iid, + "stop_command_seconds": stop_cmd_seconds, + "before": gen.window(0, rel), + "first_10s_after_stop": gen.window(rel, rel + 10), + "first_success_after_stop_s": gen.first_success_after(t_stop), + "max_gap_without_success_after_stop_s": gen.max_gap_after(t_stop), + "stopped_instance_served_after_3s": later.count(iid), + "instances_after_stop": sorted(set(later)), + **gen.verify(), + } + t_start = time.monotonic() + run(args.start_cmd, id=cid) + res["rejoin_seconds"] = wait_served(api, iid) + res["rejoin_including_start_s"] = round(time.monotonic() - t_start, 2) + results.append(res) + print(json.dumps(res, ensure_ascii=False, indent=2)) + r.check(res["max_gap_without_success_after_stop_s"] <= 10, f"writes resumed within 10 s after stopping {iid}") + r.check(res["stopped_instance_served_after_3s"] == 0, f"stopped {iid} not served after detection") + r.check(res["lost_or_changed"] == 0, "confirmed messages preserved") + r.check(res["duplicate_texts"] == 0, "no duplicates despite retries with the same key") + r.check(res["rejoin_seconds"] >= 0, f"{iid} rejoined the LB after restart") + if args.output: + with open(args.output, "w", encoding="utf-8") as f: + json.dump({"workload": f"{args.workers} closed-loop writers, retry same key on failure, " + f"{args.before}s before + {args.after}s after stop", + "replicas": results}, f, ensure_ascii=False, indent=2) + r.finish() + + +if __name__ == "__main__": + main() diff --git a/student-tests/idempotency.py b/student-tests/idempotency.py new file mode 100644 index 00000000..fc4c5979 --- /dev/null +++ b/student-tests/idempotency.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +""" +Общая идемпотентность POST сообщения через LB (lab3). + + python student-tests/idempotency.py --base-url http://localhost:8080 + +Проверяет: параллельные запросы с ОДНИМ ключом через разные реплики дают одно +сообщение; другой body с тем же ключом → 409; ключ без/неверного формата → 400; +порядок/пробелы в JSON не важны; область ключа — пользователь + чат. +""" +import argparse +import json +import uuid +from concurrent.futures import ThreadPoolExecutor + +from common import Api, Report + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8080") + ap.add_argument("--parallel", type=int, default=20) + api, r = Api(ap.parse_args().base_url), Report() + args = ap.parse_args() + + alice, bob = api.new_user("idem_a"), api.new_user("idem_b") + st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "idem", "member_ids": [alice["id"], bob["id"]]}, + token=alice["token"]) + st, chat2, _ = api.call("POST", "/api/v1/chats", {"title": "idem2", "member_ids": [alice["id"]]}, + token=alice["token"]) + path, path2 = f"/api/v1/chats/{chat['id']}/messages", f"/api/v1/chats/{chat2['id']}/messages" + + def history(p, token): + st, page, _ = api.call("GET", p + "?limit=100", token=token) + return page["items"] + + print(f"== {args.parallel} параллельных запросов с одним ключом ==") + key, text = uuid.uuid4().hex, "одно сообщение " + uuid.uuid4().hex[:6] + + def send(_): + return api.call("POST", path, {"text": text}, token=alice["token"], headers={"Idempotency-Key": key}) + + with ThreadPoolExecutor(max_workers=args.parallel) as pool: + res = list(pool.map(send, range(args.parallel))) + codes = [x[0] for x in res] + ids = {x[1]["id"] for x in res if x[0] == 201} + instances = {x[2].get("X-Instance-Id") for x in res} + r.check(codes.count(201) == args.parallel, f"all parallel repeats -> 201 (got {sorted(set(codes))})") + r.check(len(ids) == 1, f"all responses carry the same message id ({len(ids)} distinct)") + r.check(len(instances) >= 2, f"requests were served by >=2 replicas ({len(instances)})") + r.check(sum(m["text"] == text for m in history(path, alice["token"])) == 1, "exactly one message in history") + first = res[0][1] + r.check(all(x[1] == first for x in res), "every replay returns the identical Message") + + print("== семантика ключа ==") + st, _, _ = api.call("POST", path, {"text": "другой текст"}, token=alice["token"], headers={"Idempotency-Key": key}) + r.check(st == 409, f"same key, different body -> 409 (got {st})") + raw = ('{ "text" : ' + json.dumps(text, ensure_ascii=False) + ' }').encode() + st, body, _ = api.raw("POST", path, raw, {"Content-Type": "application/json", "Idempotency-Key": key, + "Authorization": "Bearer " + alice["token"]}) + r.check(st == 201 and json.loads(body)["id"] == first["id"], f"other JSON formatting = same request (got {st})") + st, other, _ = api.call("POST", path2, {"text": text}, token=alice["token"], headers={"Idempotency-Key": key}) + r.check(st == 201 and other["id"] != first["id"], "same key in another chat is independent") + st, bobs, _ = api.call("POST", path, {"text": text}, token=bob["token"], headers={"Idempotency-Key": key}) + r.check(st == 201 and bobs["id"] != first["id"] and bobs["sender_id"] == bob["id"], + "same key from another user is independent") + st, _, _ = api.raw("POST", path, json.dumps({"text": "без ключа"}).encode(), + {"Content-Type": "application/json", "Authorization": "Bearer " + alice["token"]}) + r.check(st == 400, f"missing Idempotency-Key -> 400 (got {st})") + for bad in ("has space", "x" * 129, "slash/key"): + st, _, _ = api.call("POST", path, {"text": "bad key"}, token=alice["token"], + headers={"Idempotency-Key": bad}) + r.check(st == 400, f"invalid key {bad[:12]!r}... -> 400 (got {st})") + st, _, _ = api.call("POST", path, {"text": text}, headers={"Idempotency-Key": key}) + r.check(st == 401, f"replay without session -> 401, access re-checked (got {st})") + + print("== неопределённый результат: клиент повторяет с тем же ключом ==") + key2 = uuid.uuid4().hex + try: + api.call("POST", path, {"text": "таймаут?"}, token=alice["token"], headers={"Idempotency-Key": key2}, + timeout=0.001) + except OSError: + pass # ответ не дождались: записано или нет — неизвестно + st, again, _ = api.call("POST", path, {"text": "таймаут?"}, token=alice["token"], headers={"Idempotency-Key": key2}) + r.check(st == 201, "retry after uncertain result -> 201") + r.check(sum(m["text"] == "таймаут?" for m in history(path, alice["token"])) == 1, "still exactly one message") + r.finish() + + +if __name__ == "__main__": + main() diff --git a/student-tests/loadgen.py b/student-tests/loadgen.py new file mode 100644 index 00000000..b76e62dd --- /dev/null +++ b/student-tests/loadgen.py @@ -0,0 +1,110 @@ +""" +Генератор записей для экспериментов отказа и rolling update (lab3, уровень «4»). + +Несколько потоков в замкнутом цикле отправляют сообщения через LB. У каждого +сообщения свой Idempotency-Key; если ответ не получен (ошибка/таймаут/5xx), +поток повторяет ТОТ ЖЕ запрос с ТЕМ ЖЕ ключом — так проверяется, что +неопределённая запись безопасно повторяется и не даёт дублей. +""" +import threading +import time +import uuid +from urllib.parse import quote + +from common import Api + + +class LoadGen: + def __init__(self, api: Api, token: str, chat_id: str, workers: int = 4, timeout: float = 2.0): + self.api, self.token, self.chat_id = api, token, chat_id + self.path = f"/api/v1/chats/{chat_id}/messages" + self.workers, self.timeout = workers, timeout + self.stop_event = threading.Event() + self.lock = threading.Lock() + self.ok = [] # (t, instance, message) + self.errors = [] # (t, reason) + self.retried = 0 # сколько раз повторяли тот же ключ + self.threads = [] + self.t0 = None + + def _worker(self, w: int): + i = 0 + while not self.stop_event.is_set(): + key = uuid.uuid4().hex + text = f"load-{w}-{i}-{key[:8]}" + first = True + while not self.stop_event.is_set(): + if not first: + with self.lock: + self.retried += 1 + first = False + try: + st, body, rh = self.api.call("POST", self.path, {"text": text}, token=self.token, + headers={"Idempotency-Key": key}, timeout=self.timeout) + except OSError as exc: + st, body, rh = None, None, None + reason = type(exc).__name__ + else: + reason = f"HTTP {st}" + now = time.monotonic() + if st == 201: + with self.lock: + self.ok.append((now, rh.get("X-Instance-Id", ""), body)) + break + with self.lock: + self.errors.append((now, reason)) + time.sleep(0.1) # повтор с тем же ключом + i += 1 + + def start(self): + self.t0 = time.monotonic() + for w in range(self.workers): + t = threading.Thread(target=self._worker, args=(w,), daemon=True) + t.start() + self.threads.append(t) + + def stop(self): + self.stop_event.set() + for t in self.threads: + t.join(timeout=self.timeout + 2) + + # ---------------------------------------------------------------- метрики + def window(self, a: float, b: float) -> dict: + """Успехи/ошибки в окне [a, b) секунд от старта нагрузки.""" + ok = [x for x in self.ok if a <= x[0] - self.t0 < b] + err = [x for x in self.errors if a <= x[0] - self.t0 < b] + dur = max(b - a, 1e-9) + return {"successful": len(ok), "errors": len(err), "successful_rps": round(len(ok) / dur, 1)} + + def max_gap_after(self, t_abs: float) -> float: + """Самый длинный промежуток без успешной записи после момента t_abs (сек).""" + times = [t_abs] + sorted(x[0] for x in self.ok if x[0] >= t_abs) + if len(times) == 1: + return float("inf") + return round(max(b - a for a, b in zip(times, times[1:])), 3) + + def first_success_after(self, t_abs: float): + later = sorted(x[0] for x in self.ok if x[0] >= t_abs) + return round(later[0] - t_abs, 3) if later else None + + def instances_after(self, t_abs: float) -> list: + return [x[1] for x in sorted(self.ok) if x[0] >= t_abs] + + def verify(self) -> dict: + """Все подтверждённые сообщения есть в истории без изменений, дублей нет.""" + items, cursor = [], None + while True: + q = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "") + st, page, _ = self.api.call("GET", self.path + q, token=self.token) + assert st == 200, f"history read failed: {st}" + items += page["items"] + cursor = page["next_cursor"] + if cursor is None: + break + by_id = {m["id"]: m for m in items} + texts = [m["text"] for m in items] + confirmed = [x[2] for x in self.ok] + lost = [m for m in confirmed if by_id.get(m["id"]) != m] + return {"history_messages": len(items), "confirmed": len(confirmed), + "lost_or_changed": len(lost), "duplicate_texts": len(texts) - len(set(texts)), + "retries_with_same_key": self.retried} diff --git a/student-tests/logout_cache.py b/student-tests/logout_cache.py new file mode 100644 index 00000000..04ae3725 --- /dev/null +++ b/student-tests/logout_cache.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +""" +Logout при приостановленном Redis (замечание к app/sessions.py). + +Сценарий преподавателя: прогреть сессию в кэше, приостановить Redis, сделать +logout, восстановить Redis и проверить старый токен. +Требование: 204 только при гарантированном отзыве; после 204 старый токен +никогда не принимается, в том числе после восстановления Redis. + + python student-tests/logout_cache.py --base-url http://localhost:8080 +(по умолчанию сам делает docker compose pause/unpause redis) +""" +import argparse +import shlex +import subprocess +import time + +from common import Api, Report + +COMPOSE = "docker compose --env-file .env" + + +def sh(cmd: str): + print(f" $ {cmd}") + subprocess.run(shlex.split(cmd), check=True, stdout=subprocess.DEVNULL) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8080") + ap.add_argument("--pause-redis", default=f"{COMPOSE} pause redis") + ap.add_argument("--unpause-redis", default=f"{COMPOSE} unpause redis") + args = ap.parse_args() + api, r = Api(args.base_url), Report() + + user = api.new_user("logoutcache") + token = user["token"] + for _ in range(2): # первый запрос кладёт сессию в Redis, второй читает из кэша + st, _, _ = api.call("GET", "/api/v1/users/me", token=token) + r.check(st == 200, "session is warmed up in cache") + + print("== Redis приостановлен ==") + sh(args.pause_redis) + try: + st_logout, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=token) + r.check(st_logout != 204, + f"logout is NOT confirmed while cache cannot be invalidated (got {st_logout}, expected 503)") + finally: + sh(args.unpause_redis) + time.sleep(0.5) + + print("== Redis восстановлен ==") + st, _, _ = api.call("GET", "/api/v1/users/me", token=token) + if st_logout == 204: + r.check(st == 401, f"after a 204 the old token is rejected after Redis recovery (got {st})") + else: + r.check(st == 200, f"unconfirmed logout left the session consistent and valid (got {st})") + st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=token) + r.check(st == 204, f"retry logout after Redis recovery -> 204 (got {st})") + st, _, _ = api.call("GET", "/api/v1/users/me", token=token) + r.check(st == 401, f"old token after confirmed logout -> 401, no stale cache copy (got {st})") + st, _, _ = api.call("GET", "/api/v1/users/me", token=token) + r.check(st == 401, f"old token still rejected on repeat (got {st})") + r.finish() + + +if __name__ == "__main__": + main() diff --git a/student-tests/outage.py b/student-tests/outage.py new file mode 100644 index 00000000..f6e73438 --- /dev/null +++ b/student-tests/outage.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +""" +Недоступность зависимостей (уровень «4»). Сам останавливает и запускает контейнеры: + python student-tests/outage.py --base-url http://localhost:8080 + +1. Redis остановлен → API работает в обход кэша (сессии читаются из PostgreSQL). +2. PostgreSQL остановлен → защищённые запросы получают ограниченную ошибку 503, + неизвестный токен НЕ принимается (никогда 200), /health/ready = 503. +3. PostgreSQL запущен снова → тот же токен снова работает, данные на месте. +""" +import argparse +import shlex +import subprocess +import time +import uuid + +from common import Api, Report + +COMPOSE = "docker compose --env-file .env" + + +def sh(cmd: str): + print(f" $ {cmd}") + subprocess.run(shlex.split(cmd), check=True, stdout=subprocess.DEVNULL) + + +def wait_ready(api: Api, seconds=90): + deadline = time.time() + seconds + while time.time() < deadline: + try: + if api.raw("GET", "/health/ready", timeout=3)[0] == 200: + return True + except OSError: + pass + time.sleep(1) + return False + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8080") + ap.add_argument("--stop-redis", default=f"{COMPOSE} stop redis") + ap.add_argument("--start-redis", default=f"{COMPOSE} start redis") + ap.add_argument("--stop-db", default=f"{COMPOSE} stop postgres") + ap.add_argument("--start-db", default=f"{COMPOSE} start postgres") + args = ap.parse_args() + api, r = Api(args.base_url), Report() + + user = api.new_user("outage") + st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "outage", "member_ids": [user["id"]]}, token=user["token"]) + path = f"/api/v1/chats/{chat['id']}/messages" + api.call("POST", path, {"text": "before outage"}, token=user["token"]) + + print("== 1. Redis недоступен ==") + sh(args.stop_redis) + try: + st, _, _ = api.call("GET", "/api/v1/users/me", token=user["token"]) + r.check(st == 200, "valid token still works without Redis (cache bypassed)") + st, _, _ = api.call("POST", path, {"text": "without redis"}, token=user["token"]) + r.check(st == 201, "writes still work without Redis") + fresh = api.register("noredis") + st, sess, _ = api.login(fresh["username"], fresh["password"]) + r.check(st == 201, "login works without Redis") + st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex) + r.check(st == 401, "forged token still rejected without Redis") + finally: + sh(args.start_redis) + + print("== 2. PostgreSQL недоступен ==") + sh(args.stop_db) + try: + time.sleep(1) + st, _, _ = api.call("GET", path, token=user["token"]) + r.check(st == 503, f"history without DB -> 503, not a hang (got {st})") + st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex) + r.check(st in (401, 503), f"unknown token is never trusted without DB (got {st})") + st, _, _ = api.call("GET", "/api/v1/users/me") + r.check(st == 401, "anonymous request -> 401") + st = api.raw("GET", "/health/ready")[0] + r.check(st == 503, "/health/ready -> 503") + st = api.raw("GET", "/health/live")[0] + r.check(st == 200, "/health/live -> 200 (process is alive)") + finally: + sh(args.start_db) + + print("== 3. восстановление ==") + r.check(wait_ready(api), "/health/ready back to 200") + st, page, _ = api.call("GET", path, token=user["token"]) + texts = [m["text"] for m in (page or {}).get("items", [])] + r.check(st == 200 and "before outage" in texts and "without redis" in texts, + "same token reads the same history after DB is back") + r.finish() + + +if __name__ == "__main__": + main() diff --git a/student-tests/race.py b/student-tests/race.py new file mode 100644 index 00000000..d65b8ab7 --- /dev/null +++ b/student-tests/race.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +""" +Конкурентная запись: 10 клиентов параллельно отправляют по 10 сообщений. +Ожидаем ровно 100 уникальных сообщений в истории. + python student-tests/race.py --base-url http://localhost:8080 +""" +import argparse +from concurrent.futures import ThreadPoolExecutor + +from common import Api + +CLIENTS, PER_CLIENT = 10, 10 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8080") + api = Api(ap.parse_args().base_url) + user = api.new_user("race") + st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "race", "member_ids": [user["id"]]}, token=user["token"]) + mpath = f"/api/v1/chats/{chat['id']}/messages" + + def worker(w): + return [api.call("POST", mpath, {"text": f"c{w}-m{i}"}, token=user["token"])[0] for i in range(PER_CLIENT)] + + with ThreadPoolExecutor(max_workers=CLIENTS) as pool: + codes = [c for batch in pool.map(worker, range(CLIENTS)) for c in batch] + + ids, texts, cursor = [], [], None + while True: + st, page, _ = api.call("GET", f"{mpath}?limit=50" + (f"&cursor={cursor}" if cursor else ""), token=user["token"]) + ids += [m["id"] for m in page["items"]] + texts += [m["text"] for m in page["items"]] + cursor = page["next_cursor"] + if cursor is None: + break + expected = {f"c{w}-m{i}" for w in range(CLIENTS) for i in range(PER_CLIENT)} + ok = codes.count(201) == 100 and len(ids) == 100 and len(set(ids)) == 100 and set(texts) == expected + print(f"sent=100 accepted={codes.count(201)} received={len(ids)} unique_ids={len(set(ids))} " + f"all_texts_present={set(texts) == expected}") + print("PASS" if ok else "FAIL") + raise SystemExit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/student-tests/rollback_check.py b/student-tests/rollback_check.py new file mode 100644 index 00000000..0a8a0994 --- /dev/null +++ b/student-tests/rollback_check.py @@ -0,0 +1,52 @@ +""" +Rollback составной операции «создать чат + участников» (уровень «4»). + +Создаём чат, где последний участник — несуществующий пользователь. Проверку +приложения нарочно обходим и вызываем запись напрямую: первый INSERT в chats +проходит, а вставка участника падает на внешнем ключе. Ожидаем, что транзакция +откатилась целиком: ни чата, ни участников в базе нет. + +Запуск внутри контейнера API (у него есть доступ к БД и коду): + docker compose cp student-tests/rollback_check.py api:/tmp/rollback_check.py + docker compose exec api python /tmp/rollback_check.py +Локально без Docker: python student-tests/rollback_check.py +""" +import asyncio +import sys +import uuid +from pathlib import Path + +sys.path.insert(0, str(Path.cwd())) +import psycopg # noqa: E402 + +from app import repo # noqa: E402 +from app.config import settings # noqa: E402 + + +async def main() -> int: + title = "rollback-" + uuid.uuid4().hex[:8] + async with await psycopg.AsyncConnection.connect(settings.database_url) as conn: + creator = await repo.create_user(conn, "rb_" + uuid.uuid4().hex[:10], "rb", "x") + await conn.commit() + ghost = uuid.uuid4() # такого пользователя нет + try: + async with conn.transaction(): + await repo.insert_chat(conn, title, [uuid.UUID(creator["id"]), ghost], creator["id"]) + print("FAIL - insert unexpectedly succeeded") + return 1 + except psycopg.errors.ForeignKeyViolation: + print(" ok - insert of unknown member failed on foreign key") + cur = await conn.execute( + "SELECT count(*) FROM chats WHERE title = %s", (title,)) + chats = (await cur.fetchone())[0] + cur = await conn.execute( + "SELECT count(*) FROM chat_members m JOIN chats c ON c.id = m.chat_id WHERE c.title = %s", (title,)) + members = (await cur.fetchone())[0] + ok = chats == 0 and members == 0 + print(f" {'ok ' if ok else 'FAIL'} - after rollback: chats={chats}, members={members} (expected 0, 0)") + print("PASS" if ok else "FAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(asyncio.run(main())) diff --git a/student-tests/rolling_update.py b/student-tests/rolling_update.py new file mode 100644 index 00000000..29c5a1ea --- /dev/null +++ b/student-tests/rolling_update.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +""" +Поочерёдная замена реплик API (rolling update) под нагрузкой (lab3, уровень «4»). + +Compose не делает rolling update сам, поэтому замена выполняется по шагам: + 1. собрать новый образ (docker compose build api); + 2. для каждой старой реплики: + поднять ОДНУ новую (up --scale api=N+1 --no-recreate) → дождаться healthy + и того, что LB её обслуживает → остановить старую (SIGTERM, graceful) → удалить; + 3. всё это время нагрузка пишет сообщения через LB и повторяет неудачные + запросы с тем же Idempotency-Key. +Итог: ошибки/RPS во время замены, все реплики на новом образе, нет потерь и дублей. + +Миграции: перед заменой выполняется сервис migrate (однократно). Новые миграции +должны быть совместимы с ещё работающей старой версией (только добавление). + + python student-tests/rolling_update.py --base-url http://localhost:8080 --output evidence/rolling-update.json +""" +import argparse +import json +import shlex +import subprocess +import time + +from common import Api, Report +from failover_each import served_instances +from loadgen import LoadGen + +COMPOSE = "docker compose --env-file .env" + + +def sh(cmd: str) -> str: + print(f" $ {cmd}") + return subprocess.run(shlex.split(cmd), check=True, capture_output=True, text=True).stdout + + +def api_ids() -> list: + return [x.strip() for x in sh(f"{COMPOSE} ps -q api").splitlines() if x.strip()] + + +def image_of(cid: str) -> str: + return sh(f"docker inspect -f {{{{.Image}}}} {cid}").strip() + + +def wait_healthy(cid: str, seconds: float = 90) -> bool: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if sh(f"docker inspect -f {{{{.State.Health.Status}}}} {cid}").strip() == "healthy": + return True + time.sleep(1) + return False + + +def wait_served(api: Api, iid: str, seconds: float = 60) -> bool: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if iid in served_instances(api, 10): + return True + time.sleep(0.5) + return False + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8080") + ap.add_argument("--workers", type=int, default=4) + ap.add_argument("--no-build", action="store_true", help="не пересобирать образ") + ap.add_argument("--output", default=None) + args = ap.parse_args() + api, r = Api(args.base_url), Report() + + if not args.no_build: + sh(f"{COMPOSE} build api") + sh(f"{COMPOSE} run --rm migrate") # однократные миграции до замены + new_image = sh("docker image inspect -f {{.Id}} mtusi-messenger:lab3").strip() + old = api_ids() + n = len(old) + r.check(n >= 2, f"{n} replicas before update") + old_images = {cid[:12]: image_of(cid) for cid in old} + + user = api.new_user("rolling") + st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "rolling", "member_ids": [user["id"]]}, + token=user["token"]) + gen = LoadGen(api, user["token"], chat["id"], workers=args.workers) + gen.start() + time.sleep(3) + t_begin = time.monotonic() + steps = [] + for cid in old: + before = set(api_ids()) + sh(f"{COMPOSE} up -d --no-deps --no-recreate --scale api={len(before) + 1} api") + new = sorted(set(api_ids()) - before) + r.check(len(new) == 1, f"one new replica started for {cid[:12]}") + new_id = new[0] + healthy = wait_healthy(new_id) + served = wait_served(api, new_id[:12]) + t0 = time.monotonic() + sh(f"docker stop -t 15 {cid}") + sh(f"docker rm {cid}") + steps.append({"old": cid[:12], "new": new_id[:12], "new_healthy": healthy, "new_served_by_lb": served, + "old_stop_seconds": round(time.monotonic() - t0, 2)}) + r.check(healthy and served, f"new replica {new_id[:12]} healthy and in LB before old {cid[:12]} stops") + t_end = time.monotonic() + time.sleep(3) + gen.stop() + + final = api_ids() + rel_a, rel_b = t_begin - gen.t0, t_end - gen.t0 + result = { + "replicas_before": sorted(old_images), "replicas_after": sorted(c[:12] for c in final), + "all_on_new_image": all(image_of(c) == new_image for c in final), + "steps": steps, + "update_duration_s": round(t_end - t_begin, 1), + "before_update": gen.window(0, rel_a), + "during_update": gen.window(rel_a, rel_b), + "after_update": gen.window(rel_b, rel_b + 3), + "max_gap_without_success_s": gen.max_gap_after(t_begin), + "instances_serving_at_end": sorted(set(gen.instances_after(t_end))), + **gen.verify(), + } + print(json.dumps(result, ensure_ascii=False, indent=2)) + r.check(len(final) == n, f"replica count restored to {n}") + r.check(result["all_on_new_image"], "all replicas run the new image") + r.check(not set(result["instances_serving_at_end"]) & set(old_images), "old replicas no longer serve traffic") + r.check(result["lost_or_changed"] == 0 and result["duplicate_texts"] == 0, "no lost or duplicated writes") + if args.output: + with open(args.output, "w", encoding="utf-8") as f: + json.dump(result, f, ensure_ascii=False, indent=2) + r.finish() + + +if __name__ == "__main__": + main() diff --git a/student-tests/run.py b/student-tests/run.py new file mode 100644 index 00000000..312d17cb --- /dev/null +++ b/student-tests/run.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +""" +Собственные тесты lab2 (запуск одной командой): + python student-tests/run.py --base-url http://localhost:8080 + +Негативные сценарии lab1 на новой аутентификации + проверки уровня «4»: +неверный пароль, logout, X-User-Id/Basic не дают доступ, гонка регистрации. +""" +import argparse +import base64 +import json +import uuid +from concurrent.futures import ThreadPoolExecutor + +from common import PASSWORD, Api, Report + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8080") + api = Api(ap.parse_args().base_url) + r = Report() + + alice, bob, eve = api.new_user("alice"), api.new_user("bob"), api.new_user("eve") + st, chat, _ = api.call("POST", "/api/v1/chats", + {"title": "own tests", "member_ids": [alice["id"], bob["id"]]}, token=alice["token"]) + assert st == 201, st + mpath = f"/api/v1/chats/{chat['id']}/messages" + + print("== аутентификация ==") + st, _, rh = api.login(alice["username"], "Wrong-password-123") + r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Basic"), "wrong password -> 401 + Basic challenge") + st, _, _ = api.login("no_such_user_" + uuid.uuid4().hex[:8], PASSWORD) + r.check(st == 401, "unknown user -> 401 (same as wrong password)") + st, _, rh = api.call("GET", "/api/v1/users/me") + r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Bearer"), "no token -> 401 + Bearer challenge") + st, _, _ = api.call("GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]}) + r.check(st == 401, "X-User-Id alone gives no access") + st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex) + r.check(st == 401, "unknown/forged token -> 401") + basic = base64.b64encode(f"{alice['username']}:{alice['password']}".encode()).decode() + st, _, _ = api.call("GET", "/api/v1/users/me", headers={"Authorization": "Basic " + basic}) + r.check(st == 401, "Basic on business endpoint -> 401") + st, me, _ = api.call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": eve["id"]}) + r.check(st == 200 and me["id"] == alice["id"], "X-User-Id cannot override bearer identity") + st, _, _ = api.call("POST", "/api/v1/users", {"username": "short_pw_" + uuid.uuid4().hex[:6], + "display_name": "x", "password": "short"}) + r.check(st == 400, "password shorter than 12 -> 400") + + print("== logout ==") + tmp = api.new_user("logout") + st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=tmp["token"]) + r.check(st == 204, "logout -> 204") + st, _, _ = api.call("GET", "/api/v1/users/me", token=tmp["token"]) + r.check(st == 401, "token after logout -> 401") + st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=tmp["token"]) + r.check(st == 401, "second logout -> 401") + + print("== гонка регистрации одного username ==") + name = "race_" + uuid.uuid4().hex[:10] + + def reg(_): + st, _, _ = api.call("POST", "/api/v1/users", {"username": name, "display_name": "r", "password": PASSWORD}) + return st + + with ThreadPoolExecutor(max_workers=20) as pool: + codes = list(pool.map(reg, range(20))) + r.check(codes.count(201) == 1 and codes.count(409) == 19, + f"20 parallel registrations -> one 201, nineteen 409 (got {sorted(codes)})") + + print("== ошибки и доступ (из lab1) ==") + st, _, _ = api.raw("POST", "/api/v1/users", b"{not json", {"Content-Type": "application/json"}) + r.check(st == 400, "malformed JSON -> 400") + st, _, _ = api.call("POST", "/api/v1/users", {"username": alice["username"], "display_name": "d", "password": PASSWORD}) + r.check(st == 409, "duplicate username -> 409") + st, _, _ = api.call("POST", mpath, {"text": " "}, token=alice["token"]) + r.check(st == 400, "blank message -> 400") + st, _, _ = api.call("POST", mpath, {"text": "x", "sender_id": eve["id"]}, token=alice["token"]) + r.check(st == 400, "sender_id in body is rejected") + st, _, _ = api.call("POST", mpath, {"text": "чужое"}, token=eve["token"]) + r.check(st == 404, "outsider POST to foreign chat -> 404") + st, _, _ = api.call("GET", mpath, token=eve["token"]) + r.check(st == 404, "outsider GET foreign history -> 404") + st, _, _ = api.call("GET", "/api/v1/chats/not-a-uuid", token=alice["token"]) + r.check(st == 400, "invalid chat uuid -> 400") + + print("== пагинация ==") + for i in range(5): + api.call("POST", mpath, {"text": f"m{i}"}, token=bob["token"]) + seen, cursor, pages = [], None, 0 + while pages < 10: + st, page, _ = api.call("GET", f"{mpath}?limit=2" + (f"&cursor={cursor}" if cursor else ""), token=alice["token"]) + pages += 1 + seen += [m["id"] for m in page["items"]] + cursor = page["next_cursor"] + if cursor is None: + break + r.check(len(seen) == 5 and len(set(seen)) == 5 and pages == 3, "5 messages / limit 2 -> 3 pages, no duplicates") + st, other, _ = api.call("POST", "/api/v1/chats", {"title": "other", "member_ids": [alice["id"]]}, token=alice["token"]) + st, p, _ = api.call("GET", f"{mpath}?limit=1", token=alice["token"]) + st, _, _ = api.call("GET", f"/api/v1/chats/{other['id']}/messages?cursor={p['next_cursor']}", token=alice["token"]) + r.check(st == 400, "cursor from another chat -> 400") + + print("== Content-Type ==") + body = json.dumps({"username": "ct_" + uuid.uuid4().hex[:8], "display_name": "c", "password": PASSWORD}).encode() + st, _, _ = api.raw("POST", "/api/v1/users", body, {"Content-Type": "text/plain"}) + r.check(st == 415, f"valid JSON with text/plain -> 415 (got {st})") + st, _, _ = api.raw("POST", mpath, json.dumps({"text": "x"}).encode(), + {"Content-Type": "text/plain", "Authorization": "Bearer " + alice["token"]}) + r.check(st == 415, f"message with text/plain -> 415 (got {st})") + st, _, _ = api.raw("POST", "/api/v1/chats", b"{}", {"Content-Type": "text/plain"}) + r.check(st == 401, f"text/plain without token -> 401 first (got {st})") + st, _, _ = api.raw("POST", mpath, json.dumps({"text": "utf8"}).encode(), + {"Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + alice["token"], + "Idempotency-Key": uuid.uuid4().hex}) + r.check(st == 201, f"application/json; charset=utf-8 accepted (got {st})") + + r.finish() + + +if __name__ == "__main__": + main()