Author SHA1 Message Date
Chernikov a13ed1925e на 4 2026-10-21 18:25:07 +03:00
48 changed files with 4967 additions and 24 deletions
+20
View File
@@ -18,3 +18,23 @@ __pycache__
node_modules node_modules
evidence evidence
.DS_Store .DS_Store
# В образ копируются только requirements.txt, migrations/ и src/.
**/__pycache__
**/*.pyc
contracts
examples
scripts
tests
student-tests
infra
*.md
Makefile
lab.json
requirements-dev.txt
requirements.in
compose*.yaml
.gitignore
.gitattributes
.vscode
.idea
*.log
+16 -9
View File
@@ -1,13 +1,20 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Copy to .env for your LOCAL synthetic test environment; never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md. # docker compose reads .env to fill ${...} in compose.yaml; every value has a default there.
APP_HOST=0.0.0.0 # Passwords are NOT here: they are files in secrets/ (python scripts/init_secrets.py).
APP_PORT=8080
APP_ENV=lab APP_ENV=lab
SESSION_TTL_SECONDS=3600 APP_LOG_LEVEL=INFO
# Choose credentials locally. File paths contain no secret values. # Seconds for graceful stop after SIGTERM (<= 10) and, inside it, how long a replica keeps
DATABASE_URL_FILE=/run/secrets/database_url # serving while reporting "not ready" so that the load balancer removes it first.
# Optional on 3, required use on 4 in lab2; Redis OR Valkey: APP_SHUTDOWN_TIMEOUT=8
SESSION_STORE=postgres APP_DRAIN_DELAY=3
CACHE_URL_FILE=/run/secrets/cache_url # Load balancer ports on 127.0.0.1 of the host (API replicas are not published).
APP_PUBLISHED_PORT=8080
LB_STATS_PORT=8404
API_REPLICAS=2 API_REPLICAS=2
SESSION_TTL_SECONDS=3600
IDEMPOTENCY_TTL_SECONDS=86400 IDEMPOTENCY_TTL_SECONDS=86400
DB_POOL_SIZE=10
# Fixed inside the containers by compose.yaml (skeleton names kept):
# APP_HOST=0.0.0.0 APP_PORT=8080
# DATABASE_URL_FILE=/run/secrets/database_url CACHE_URL_FILE=/run/secrets/cache_url
# SESSION_STORE from the skeleton is not needed: sessions are always stored in Valkey.
+10
View File
@@ -0,0 +1,10 @@
# Файлы, которые выполняются или читаются внутри Linux-контейнеров, всегда с LF,
# даже при checkout в Windows с core.autocrlf=true.
*.sh text eol=lf
*.sql text eol=lf
*.conf text eol=lf
*.cfg text eol=lf
compose.yaml text eol=lf
Dockerfile text eol=lf
# cmd.exe ожидает CRLF.
*.cmd text eol=crlf
+105
View File
@@ -0,0 +1,105 @@
# Шпаргалка для защиты — лабораторная 3
Команды по порядку сценария защиты из README. Подробности решения — в [REPORT.md](REPORT.md).
Shell: **Git Bash** в Windows или обычный терминал в Linux/macOS (в Linux вместо `python -X utf8` — `python3`).
`-X utf8` в Windows обязателен для публичных тестов: они читают контракт в кодировке системы (cp1251), а в контракте lab3 есть символы, которых в ней нет.
Адрес — `127.0.0.1`, а не `localhost`: в Windows `localhost` сначала пробует IPv6, и каждый запрос идёт около двух секунд.
## 0. Подготовка (один раз)
```sh
python scripts/init_secrets.py # случайные пароли в secrets/, в Git не попадают
cp .env.example .env
URL=http://127.0.0.1:8080
# post <путь> [токен] [Idempotency-Key] — JSON со стандартного ввода; печатает код и реплику
post() { curl -s -X POST "$URL$1" -H 'Content-Type: application/json' ${2:+-H "Authorization: Bearer $2"} ${3:+-H "Idempotency-Key: $3"} --data-binary @- -w '\nHTTP %{http_code} via %header{x-instance-id}\n'; }
# get <путь> [токен]
get() { curl -s "$URL$1" ${2:+-H "Authorization: Bearer $2"} -w '\nHTTP %{http_code} via %header{x-instance-id}\n'; }
# new <ПЕРЕМЕННАЯ> <путь> [токен] — как post, но ещё сохраняет id созданного объекта
new() { local r; r=$(post "$2" "$3"); echo "$r"; printf -v "$1" %s "$(echo "$r" | sed -nE 's/.*"id":"([^"]+)".*/\1/p' | head -1)"; }
# signin <ПЕРЕМЕННАЯ> <username> <password> — вход по Basic, токен сохраняется в переменную
signin() { local r; r=$(curl -s -X POST "$URL/api/v1/auth/sessions" -u "$2:$3" -w '\nHTTP %{http_code}\n'); echo "$r" | tail -1; printf -v "$1" %s "$(echo "$r" | sed -nE 's/.*"token":"([^"]+)".*/\1/p')"; }
```
## 1. Запуск и две реплики через балансировщик с одной сессией
```sh
docker compose up -d --build --wait # postgres, valkey, migrate (один раз), api x2, lb
docker compose ps # api-1, api-2 без портов; порты только у lb, на 127.0.0.1
new ALICE /api/v1/users <<< '{"username":"alice","display_name":"Алиса","password":"Alice-password-123"}'
new BOB /api/v1/users <<< '{"username":"bob","display_name":"Боб","password":"Bob-password-12345"}'
signin TA alice Alice-password-123
signin TB bob Bob-password-12345
for i in 1 2 3 4; do get /api/v1/users/me "$TA" | tail -1; done # via чередуется: две реплики, один токен
docker ps --filter label=com.docker.compose.service=api --format '{{.ID}} {{.Names}}' # X-Instance-Id = ID контейнера
python -X utf8 tests/smoke.py --base-url $URL # make test
```
Идемпотентность: тот же ключ — то же сообщение, другое тело — 409, без ключа — 400:
```sh
new CHAT /api/v1/chats "$TA" <<< "{\"title\":\"Проект по ВНП\",\"member_ids\":[\"$ALICE\",\"$BOB\"]}"
post /api/v1/chats/$CHAT/messages "$TA" key-001 <<< '{"text":"Привет, Боб!"}'
post /api/v1/chats/$CHAT/messages "$TA" key-001 <<< '{"text":"Привет, Боб!"}' # тот же id, возможно другая реплика
post /api/v1/chats/$CHAT/messages "$TA" key-001 <<< '{"text":"Другой текст"}' # 409
post /api/v1/chats/$CHAT/messages "$TA" <<< '{"text":"Без ключа"}' # 400
get /api/v1/chats/$CHAT/messages "$TB" # одно сообщение
```
## 2–3. Отказ одной реплики
Страница состояния балансировщика: <http://127.0.0.1:8404> — видно, какая реплика UP, а какая DOWN.
```sh
python -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --base-url $URL # Windows
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=$URL # Linux/macOS
docker compose ps -a # какой контейнер действительно остановлен: Exited (0)
docker compose logs lb | grep -E "is (DOWN|UP)" # HAProxy исключил его: Layer7 wrong status 503
docker compose up -d --wait # вернуть реплику
# повторить тест: если остановлена та же реплика, запустить ещё раз, пока не будет вторая
```
## 4. Перезапуск всего стенда с тем же токеном
```sh
python -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url $URL # Windows
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=$URL # Linux/macOS
get /api/v1/chats/$CHAT/messages "$TA" # после перезапуска: те же данные, тот же токен
```
## Уровень «4»
Каждый пункт можно показать отдельно (скрипт сам печатает команды и вывод):
```sh
python -X utf8 scripts/lab3_checks.py --only stack # лимиты CPU/RAM, порты только у lb, секреты, нет container_name
python -X utf8 scripts/lab3_checks.py --only idempotency # 20 одновременных запросов с одним ключом
python -X utf8 scripts/lab3_checks.py --only experiment # stop и kill каждой реплики под нагрузкой: RPS, ошибки, время
python -X utf8 scripts/lab3_checks.py --only rolling # поочерёдная замена реплик новым образом под нагрузкой
python -X utf8 scripts/lab3_checks.py --only valkey-down postgres-down
```
Плавная остановка одной реплики: в логе реплики `shutdown_started`, затем через 3 с закрытие приёма и `clean=True`:
```sh
docker stop <ID реплики>; docker logs --tail 3 <ID реплики>; docker compose up -d --wait
```
Собственные тесты:
```sh
BASE_URL=$URL python -X utf8 -m unittest discover -s student-tests -v # make student-test
BASE_URL=$URL python student-tests/race.py # make race
```
## Остановка и уборка
```sh
docker compose stop # безопасная остановка, данные остаются в volumes
docker compose down # удалить контейнеры, volumes остаются
docker compose down -v # удалить ещё и все данные
```
+41
View File
@@ -0,0 +1,41 @@
# Базовый образ закреплён и тегом версии, и digest: тег читается человеком,
# digest гарантирует те же самые слои при повторной сборке.
FROM python:3.14.7-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d
# PYTHONUNBUFFERED: логи сразу попадают в docker logs, а не ждут в буфере.
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1 \
APP_HOST=0.0.0.0 \
APP_PORT=8080
# Непривилегированный пользователь без домашнего каталога и без shell.
RUN groupadd --gid 10001 app \
&& useradd --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
WORKDIR /app
# Сначала только lock-файл: слой с пакетами пересобирается лишь при изменении зависимостей.
# --require-hashes: pip ставит ровно те файлы, хеши которых записаны в requirements.txt.
# --only-binary: только готовые wheel, без компиляции во время сборки.
COPY requirements.txt ./
RUN pip install --no-cache-dir --require-hashes --only-binary=:all: --root-user-action=ignore -r requirements.txt
# Python не компилируется в отдельный бинарник, поэтому сборка одноэтапная.
# Файлы принадлежат root: процесс приложения может их читать, но не менять.
COPY migrations/ ./migrations/
COPY src/ ./
# Версия сборки попадает в лог старта: по ней видно, какие реплики уже обновлены.
ARG APP_VERSION=dev
ENV APP_VERSION=${APP_VERSION}
USER app
EXPOSE 8080
# Во время start-period Docker проверяет каждую секунду: новая реплика быстрее становится healthy.
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --start-interval=1s --retries=3 \
CMD ["python", "-m", "messenger.healthcheck"]
# exec-форма: python — процесс PID 1 и сам получает SIGTERM от docker stop.
CMD ["python", "-m", "messenger"]
+21 -1
View File
@@ -4,10 +4,12 @@ CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover .PHONY: help check validate test load test-persistence test-failover secrets up student-test race checks explain
help: help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "secrets/up: create local secrets and start the stand; student-test: own tests; race: 100 parallel messages"
@echo "checks: infrastructure checks (failover, experiment, rolling update, outages); explain: EXPLAIN of history"
check: check:
$(PYTHON) scripts/check_contract.py $(PYTHON) scripts/check_contract.py
@@ -28,3 +30,21 @@ test-persistence:
test-failover: test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
secrets:
$(PYTHON) scripts/init_secrets.py
up: secrets
docker compose up -d --build --wait
student-test:
BASE_URL="$(BASE_URL)" $(PYTHON) -m unittest discover -s student-tests -v
race:
BASE_URL="$(BASE_URL)" $(PYTHON) student-tests/race.py
checks:
$(PYTHON) scripts/lab3_checks.py
explain:
$(PYTHON) scripts/explain_history.py
+207 -14
View File
@@ -1,37 +1,230 @@
# Отчёт — лабораторная 3 # Отчёт — лабораторная 3
- Автор, группа: TODO - Автор, группа: Черников Дмитрий, БВТ2304
- Целевая оценка; выбранный трек 5, если нужен: TODO - Целевая оценка; выбранный трек 5, если нужен: 4; трек 5 не заявлен
- Commit/PR: TODO после публикации - Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO - Использованные источники, библиотеки и помощь ИИ:
- Балансировщик: HAProxy 3.4.5 (официальный образ).
- Библиотеки приложения (точные версии и хеши — в `requirements.txt`): `psycopg` 3.3.6 и `psycopg-pool` 3.3.3, `valkey` 6.1.1, `argon2-cffi` 25.1.0. Тесты и скрипты проверок — только стандартная библиотека Python.
- Источники: README, `contracts/` и `tests/` этого репозитория; [документация HAProxy 3.4](https://docs.haproxy.org/3.4/configuration.html) (health checks, resolvers, `http-error`, retries); [Compose services](https://docs.docker.com/reference/compose-file/services/); документация PostgreSQL и psycopg.
- ИИ: при написании тестов, конфигурации стенда и текста этого отчёта использовался ассистент Claude (Anthropic).
## Запуск из чистого clone ## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. Что нужно на машине: Docker с Compose v2 (проверено на Docker Desktop 29.8.1, Compose 5.5.1), Git и Python 3.9+ для тестов и скриптов проверок. `make` не обязателен: рядом с каждой командой `make` указана равнозначная. Выбран вариант **Compose + HAProxy**; Swarm не используется.
| Роль | Сервис | Образ | Готовность | Volume | Порт | Учётные данные |
| --- | --- | --- | --- | --- | --- | --- |
| Балансировщик | `lb` | `haproxy:3.4.5-trixie@sha256:7692…` | проверяет `/health/ready` каждой реплики раз в секунду | нет | `127.0.0.1:8080` (API), `127.0.0.1:8404` (страница состояния) | нет |
| API, 2 реплики | `api` (`deploy.replicas`) | `mtusi-messenger:lab3`, собирается из [Dockerfile](Dockerfile) на `python:3.14.7-slim-trixie@sha256:51da…` | `HEALTHCHECK` → `/health/ready` | нет | не публикуются, только сеть compose | секреты `database_url`, `cache_url` |
| Миграции | `migrate` | тот же образ, выполняется один раз до старта реплик | код выхода 0 | нет | нет | секрет `database_url` |
| PostgreSQL | `postgres` | `postgres:18.6-trixie@sha256:7493…` | `pg_isready` | `pgdata` | только сеть compose | `POSTGRES_PASSWORD_FILE` |
| Valkey | `valkey` | `valkey/valkey:9.0.6-trixie@sha256:6334…` | `valkey-cli ping` с паролем | `valkeydata` | только сеть compose | `requirepass` из файла секрета |
Команды для bash (в Linux вместо `python -X utf8` — `python3`):
```sh
git clone <URL fork> mtusi2026lab3 && cd mtusi2026lab3
python scripts/init_secrets.py # make secrets: случайные пароли в secrets/, в Git не попадают
cp .env.example .env # необязательно: в compose.yaml у всех значений есть умолчания
docker compose up -d --build --wait # postgres, valkey, migrate, api x2, lb; ожидание healthy
python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8080 # make test BASE_URL=http://127.0.0.1:8080
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8080
docker compose up -d --wait # вернуть остановленную тестом реплику
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8080
BASE_URL=http://127.0.0.1:8080 python -X utf8 -m unittest discover -s student-tests -v # make student-test
python -X utf8 scripts/lab3_checks.py --output evidence/lab3-checks.txt # make checks
docker compose stop # безопасная остановка: SIGTERM, данные остаются в volumes
docker compose down -v # намеренное удаление всех учебных данных (volumes)
```
Особенности Windows:
- **Кодировка.** Публичные тесты читают контракт в кодировке системы (cp1251), а в контракте lab3 есть символ, которого в ней нет. Поэтому их нужно запускать с `python -X utf8`.
- **Хуки.** Скрипты `.sh` Windows выполнить не может, поэтому у хуков есть двойники `scripts/stop-one.cmd` и `scripts/restart.cmd` с теми же действиями.
- **Адрес.** Используйте `127.0.0.1`, а не `localhost`: иначе каждый запрос ждёт около двух секунд, пока система пробует IPv6.
Действия оператора:
- **Секреты.** Один раз запустить `scripts/init_secrets.py`.
- **Миграции.** Запускаются сами: сервис `migrate` выполняется один раз до старта реплик. Повтор вручную: `docker compose run --rm migrate`.
- **Число реплик.** `API_REPLICAS` в `.env` или `docker compose up -d --scale api=3`. Балансировщик находит новые реплики сам.
- **После теста отказа.** Остановленную реплику возвращает `docker compose up -d --wait`.
- **Поочерёдное обновление.** Процедура описана ниже; автоматизирована в `scripts/lab3_checks.py --only rolling`.
Команды защиты по шагам — в [DEMO.md](DEMO.md).
## Архитектура и решения ## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. ```
клиент ──HTTP──> lb: HAProxy, 127.0.0.1:8080, round-robin, без sticky session
│ адреса реплик — из DNS Docker (имя api), проверка /health/ready раз в 1 с
├──> api-1 ──┐ пул ≤ 10 соединений на реплику ──> postgres: данные, ключи идемпотентности [pgdata]
└──> api-2 ──┘ пул ≤ 20 соединений на реплику ──> valkey: сессии, AOF [valkeydata]
migrate (один раз, до старта реплик) ──> postgres: migrations/0001…0003
```
**Что перенесено из lab2 и что изменено.**
- **Перенесено без изменения смысла:**
- PostgreSQL со схемой и миграциями, сессии в Valkey с AOF, Argon2id;
- формат API и ошибок, keyset-пагинация;
- собственные тесты и проверки отказов хранилищ.
- **Добавлено в lab3:**
- балансировщик HAProxy и реплики API;
- заголовок `X-Instance-Id`;
- обязательный `Idempotency-Key` и таблица `idempotency_keys`;
- двухшаговая остановка реплики;
- лимиты CPU/RAM;
- ограничение одновременных расчётов Argon2id;
- хуки `stop-one` и `restart`.
**Состояние вне реплик.** Реплики ничего не хранят у себя. Сессии лежат в Valkey, данные и результаты идемпотентных запросов — в PostgreSQL. Поэтому любой запрос пользователя может попасть на любую реплику без повторного входа, и sticky session не нужна.
**X-Instance-Id.** Это hostname контейнера, то есть короткий ID Docker; значение стабильно для жизни процесса. Хук `stop-one` по нему находит контейнер через `docker ps --filter id=... --filter label=com.docker.compose.service=api` и останавливает только реплику API этого проекта. Ошибки, которые создаёт сам балансировщик, заголовка `X-Instance-Id` не имеют. Они приходят в формате ошибок контракта: JSON с `X-Request-Id`.
**Балансировщик.** Конфигурация — [infra/haproxy/haproxy.cfg](infra/haproxy/haproxy.cfg).
- **Распределение.** Round-robin без sticky session. Реплики берутся из DNS Docker через `server-template` + `resolvers` (перечитывается каждую секунду), поэтому масштабирование и замена контейнеров не требуют правки конфигурации.
- **Повторы.** Запрос повторяется на другой реплике (`retry-on conn-failure`, `option redispatch`), только если соединение с репликой не установилось. Значит, запрос до неё не дошёл, и повтор безопасен даже для POST.
- **Соединения к репликам.** Закрываются после каждого ответа (`http-server-close`), поэтому запрос не уйдёт по старому соединению в реплику, которая уже закрывает приём.
**Проверки, таймауты и SIGTERM согласованы.**
| Параметр | Значение | Зачем |
| --- | --- | --- |
| Проверка готовности реплики | `GET /health/ready`, раз в 1 с; после первой неудачи — раз в 0,5 с | `/health/ready` требует PostgreSQL и Valkey и отвечает 503 после SIGTERM |
| Исключение / возврат | после 2 неудачных / 2 успешных проверок подряд | Исключение за 1–1,5 с, без ложных срабатываний от одной ошибки |
| Таймаут проверки и соединения | 1 с | Зависшая реплика не держит проверку |
| Ожидание ответа реплики (`timeout server`) | 15 с | Больше любого таймаута внутри API: ожидание пула 3 с, `lock_timeout` 3 с, `statement_timeout` 5 с |
| Остановка реплики по SIGTERM | сначала `/health/ready` = 503 и ещё 3 с (`APP_DRAIN_DELAY`) обычной работы, затем закрытие приёма и до 4 с на начатые запросы | 3 с больше времени исключения, поэтому балансировщик уходит с реплики раньше, чем она закрывает приём |
| Общий срок остановки | 8 с (`APP_SHUTDOWN_TIMEOUT`) при `stop_grace_period` 10 с | Укладывается в 10 с, Docker не доходит до SIGKILL |
Максимальное время обнаружения отказа:
- **Штатная остановка.** Балансировщик исключил реплику за 1,0–1,1 с (замерено по его странице состояния).
- **Падение процесса (`docker kill`).** Адрес исчезает из DNS Docker, и HAProxy переводит реплику в MAINT за 0,4–0,5 с. Если бы адрес остался, сработали бы проверки: две неудачи за 1–1,5 с плюс 1 с таймаута, то есть не больше 2,5 с.
**Идемпотентность.** Таблица `idempotency_keys` (миграция `0003`): область ключа — пользователь + метод + путь чата + ключ.
- **Атомарность.** Ключ и сообщение записываются одной транзакцией. Строка чата блокируется на время вставки — это нужно для порядка истории ещё с lab2. Поэтому одновременные запросы с одним ключом через разные реплики выполняются по очереди: второй находит ключ первого и возвращает то же сообщение.
- **Сравнение тел.** Тело сравнивается по sha256 от разобранного JSON, так что пробелы и экранирование не важны; другое тело с тем же ключом — 409.
- **Что запоминается.** Ответы 4xx не запоминаются: в базе ничего не меняется. При 5xx транзакция откатывается, повтор с тем же ключом безопасен.
- **Повтор.** Снова проверяет сессию и доступ.
- **Срок хранения.** Ключ хранится `IDEMPOTENCY_TTL_SECONDS` (24 ч), старые удаляет фоновая очистка.
**Миграции.** Выполняются один раз сервисом `migrate` до старта реплик, а `pg_advisory_lock` исключает гонку, даже если запустить их параллельно. Миграция lab3 только добавляет таблицу, поэтому версия API из lab2 продолжает работать на новой схеме. Ограничение: удаление или переименование колонок так не провести. Для них нужна схема expand/contract в два выпуска: сначала добавить, потом удалить, когда старых реплик не осталось. В этой работе таких изменений нет.
**Поочерёдное обновление.** В Compose нет встроенного rolling update, поэтому замена выполняется по шагам (`scripts/lab3_checks.py`, секция `rolling`):
1. Собрать новый образ и один раз применить миграции.
2. Для каждой старой реплики:
1. `docker compose up -d --no-deps --no-recreate --scale api=3 api` запускает одну новую реплику, старые остаются;
2. дождаться, пока она станет healthy и начнёт отвечать через балансировщик;
3. `docker stop` старой реплики (двухшаговая остановка) и `docker rm`.
**Ресурсы.**
- **Лимиты.** У каждого контейнера есть лимиты CPU и памяти:
| Контейнер | CPU | Память |
| --- | --- | --- |
| API, каждая реплика | 0,5 | 256 МБ |
| `lb` | 0,5 | 128 МБ |
| `postgres` | 1 | 512 МБ |
| `valkey` | 0,5 | 256 МБ |
| `migrate` | 0,5 | 128 МБ |
- **Argon2id.** Один расчёт занимает 19 МиБ памяти, поэтому реплика считает не больше 4 хешей одновременно. Остальные ждут до 5 с, затем получают 503. Пик памяти предсказуем и укладывается в лимит.
- **Соединения с БД.** Не больше 10 на реплику, то есть 20 на две реплики при `max_connections` 100.
- **Порты и `container_name`.** Наружу порты публикует только `lb`, на 127.0.0.1. `container_name` нигде нет, поэтому сервис `api` масштабируется.
**Секреты.** Каждый сервис получает только свои: `api` — `database_url` и `cache_url`, `postgres` — свой пароль, `valkey` — свой, `lb` — ни одного.
**Недоступность хранилища через балансировщик.**
- **Первые секунды.** Запросы попадают в реплики и получают от них 503: при недоступном Valkey за 1 с, при недоступном PostgreSQL за 3 с.
- **Дальше.** `/health/ready` отвечает 503 на всех репликах, балансировщик исключает их все и сам отвечает JSON 503 за 0,01 с на любой запрос.
- **Отличие от lab2.** Во время такого отказа недоступна и регистрация (в lab2 она работала без Valkey). Это осознанное следствие того, что готовность реплики включает общие хранилища. Анонимный запрос ни в каком случае не обслуживается как доверенный.
- **Восстановление.** Стенд возвращается в работу сам.
**Переменные из `.env.example`.**
| Переменная | Где используется | По умолчанию |
| --- | --- | --- |
| `APP_HOST`, `APP_PORT` | Адрес и порт API внутри контейнера, заданы в `compose.yaml` | `0.0.0.0`, `8080` |
| `APP_PUBLISHED_PORT`, `LB_STATS_PORT` | Порты балансировщика на `127.0.0.1` хоста | `8080`, `8404` |
| `API_REPLICAS` | Число реплик API | `2` |
| `APP_SHUTDOWN_TIMEOUT`, `APP_DRAIN_DELAY` | Общий срок остановки и время работы в режиме «не готов» после SIGTERM | `8`, `3` |
| `APP_ENV`, `APP_LOG_LEVEL` | Метка окружения в логе, уровень логов | `lab`, `INFO` |
| `SESSION_TTL_SECONDS` | Срок жизни сессии | `3600` |
| `IDEMPOTENCY_TTL_SECONDS` | Срок хранения ключей идемпотентности, не меньше 24 ч | `86400` |
| `DB_POOL_SIZE` | Максимум соединений с PostgreSQL на реплику | `10` |
| `DATABASE_URL_FILE`, `CACHE_URL_FILE` | Файлы секретов с адресами PostgreSQL и Valkey | `/run/secrets/database_url`, `/run/secrets/cache_url` |
| `APP_VERSION` | Версия сборки (build arg), пишется в лог старта; меняется при поочерёдном обновлении | `lab3` |
| `SESSION_STORE` | Не используется: хранилище сессий всегда Valkey | — |
## Доказательства критериев ## Доказательства критериев
Все проверки выполнены 2026-10-07 на compose-стенде: Windows 11, Docker Desktop 29.8.1, Intel Core Ultra 9 185H (16 ядер, 22 потока), 31 ГиБ RAM, лимиты контейнеров из таблицы выше. Весь трафик шёл через балансировщик.
Файлы доказательств:
- [evidence/tests.txt](evidence/tests.txt) — тесты;
- [evidence/clean-clone.txt](evidence/clean-clone.txt) — сборка и тесты из чистого clone;
- [evidence/lab3-checks.txt](evidence/lab3-checks.txt) — проверки инфраструктуры, `RESULT: PASS`, 34 из 34;
- [evidence/race.json](evidence/race.json) — конкурентный тест;
- [evidence/explain.txt](evidence/explain.txt) — планы запроса.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO | | 3: стенд в compose.yaml, ≥2 реплики, одна точка входа, общие БД и сессии | `docker compose up -d --build --wait`; секция Stack | 2 реплики `api`, порты только у `lb`, общие `postgres` и `valkey` | evidence/lab3-checks.txt, evidence/clean-clone.txt |
| Остальные пункты уровня 3 | TODO | TODO | TODO | | 3: разные запросы одного пользователя обслуживают разные реплики без повторного входа | 40 запросов `GET /users/me` с одним токеном | 20 и 20 ответов от двух разных `X-Instance-Id`, все 200 | evidence/lab3-checks.txt, раздел Balancing |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | | 3: остановка любой одной реплики; чтения и записи продолжаются не позднее 10 с | `tests/resilience.py --mode failover` с `scripts/stop-one.cmd`, повтор до остановки каждой реплики | api-4: 112 записей, 0 ошибок, первая запись после хука через 3,83 с; api-3: 106 записей, 0 ошибок, 4,13 с; обе остановлены с кодом 0 | evidence/lab3-checks.txt, раздел Public failover test |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO | | 3: повтор POST с тем же Idempotency-Key не создаёт дубль, включая конкурентный повтор и смену реплики | 20 одновременных POST с одним ключом; `test_idempotency` | Один id сообщения, ответили обе реплики, в чате одно сообщение; другое тело — 409 | evidence/lab3-checks.txt, раздел Idempotency; evidence/tests.txt |
| 3: make test, persistence, failover | smoke, оба публичных теста с хуками | Все PASS; failover видит 2 реплики до отказа | evidence/tests.txt, evidence/lab3-checks.txt |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. | 3: перезапуск всего стенда с тем же токеном | `tests/resilience.py --mode persistence` с `scripts/restart.cmd` | PASS; StartedAt сменился у обеих реплик, postgres, valkey и lb; volumes те же | evidence/lab3-checks.txt, раздел Full restart |
| 4: health/readiness, таймауты и SIGTERM согласованы, LB исключает недоступную реплику | Остановка реплики под нагрузкой; лог HAProxy | 0 ошибок клиента; HAProxy: «is DOWN, reason: Layer7 wrong status, code: 503» до закрытия приёма | evidence/lab3-checks.txt, раздел Experiment |
| 4: период проверок и максимальное время обнаружения | Страница состояния HAProxy во время эксперимента | Проверка раз в 1 с; исключение: остановка — 1,0–1,1 с, `docker kill` — 0,4–0,5 с | evidence/lab3-checks.txt, раздел Experiment |
| 4: поочерёдная остановка каждой реплики с восстановлением; RPS, ошибки, время восстановления | Секция `experiment`: stop и kill каждой реплики под нагрузкой 6 клиентов | Таблица ниже; 4858 подтверждённых записей, все в истории, дублей нет | evidence/lab3-checks.txt, раздел Experiment |
| 4: общая идемпотентность параллельными запросами с одним ключом | Секция `idempotency` | См. выше: одно сообщение на 20 запросов через 2 реплики | evidence/lab3-checks.txt |
| 4: CPU/RAM-лимиты, нет портов в обход LB, секреты только где нужно, нет container_name | Секция `stack` | Лимиты у всех 5 контейнеров; порты только у `lb` на 127.0.0.1; секреты по сервисам совпадают с таблицей выше; `container_name` нет | evidence/lab3-checks.txt, раздел Stack |
| 4: поочерёдная замена под нагрузкой | Секция `rolling` | 5582 запроса, 0 ошибок, 190 успешных RPS; обе реплики заменены новым образом по одной; 2791 запись без потерь и дублей | evidence/lab3-checks.txt, раздел Rolling update |
| 4: миграции однократно и совместимы с работающей версией | Сервис `migrate`; повторный запуск; `0003` только добавляет таблицу | Повторно `applied_now=0`, данные не задвоены | evidence/lab3-checks.txt, разделы Migrations и Rolling update |
| lab2: гонка регистрации, откат создания чата, пул, таймауты, истечение сессии, отказ Valkey/PostgreSQL, EXPLAIN | Секции `race`, `rollback`, `pool`, `timeouts`, `expiry`, `valkey-down`, `postgres-down`; `scripts/explain_history.py` | Один 201 и 19 × 409; чат откатывается целиком; максимум 20 соединений на 2 реплики; 503 через 3,02 с при блокировке; сессия истекает при TTL 2 с; 503 и восстановление после отказов; Index Scan вместо Seq Scan | evidence/lab3-checks.txt, evidence/explain.txt |
## Эксперименты и отказы ## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. **Методика.**
- Нагрузка: 6 потоков в замкнутом цикле через балансировщик. Каждый поток отправляет сообщение с новым `Idempotency-Key`, а при ошибке повторяет его с тем же ключом и телом. Потом читает `/users/me`.
- По каждой реплике по очереди: 5 с исходной нагрузки, затем `docker stop` или `docker kill`, 8 с наблюдения, `docker start` и ожидание, пока реплика снова начнёт отвечать.
- Время исключения берётся со страницы состояния HAProxy (опрос раз в 0,1 с).
- После всех прогонов история сверяется со всеми подтверждёнными записями.
| Реплика | Действие | Длительность команды, с | Успешных RPS до | RPS во время | Ошибки | Наибольший перерыв, с | Исключена LB через, с | Вернулась через, с | RPS после |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| api-3 | `docker stop` | 3,93 | 148,2 | 81,3 | 0 | 0,18 | 1,00 | 5,19 | 218,1 |
| api-4 | `docker stop` | 3,96 | 171,4 | 83,8 | 0 | 0,10 | 1,09 | 5,34 | 165,3 |
| api-3 | `docker kill` | 0,40 | 202,0 | 69,4 | 2 | 0,93 | 0,47 | 5,47 | 123,8 |
| api-4 | `docker kill` | 0,43 | 151,4 | 67,6 | 3 | 0,98 | 0,42 | 5,49 | 156,2 |
Наблюдения:
- **Штатная остановка.** Ошибок 0. Балансировщик уходит с реплики через ~1 с по её ответу 503 на `/health/ready`, а приём она закрывает только через 3 с.
- **`docker kill`.** 2–3 ошибки: это запросы, которые выполнялись в момент гибели процесса. Клиент повторил их с тем же ключом. Все 4858 подтверждённых записей оказались в истории ровно по одному разу.
- **RPS на одной реплике.** Падает примерно вдвое: у каждой реплики лимит 0,5 CPU, и одна реплика обрабатывает примерно половину нагрузки двух. После возврата второй реплики RPS восстанавливается.
- **Возврат реплики.** Около 5 с после `docker start`: старт процесса, затем две успешные проверки балансировщика.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | | Хук `stop-one` (публичный тест), каждая реплика | Записи продолжаются ≤ 10 с, нет дублей | 0 ошибок; первая запись после хука через 3,83 и 4,13 с | Потерь и дублей нет |
| Поочерёдная замена реплик новым образом | Нет ошибок клиента | 5582 запроса, 0 ошибок | Потерь и дублей нет |
| Перезапуск всего стенда хуком `restart` | Те же данные и токен | Публичный тест сохранности — PASS | 19,9 с до готовности; потерь нет |
| `docker compose stop valkey` | Ограниченный 503, нет анонимного доступа | Сначала 503 от реплик за 1,02 с, затем 503 от балансировщика за 0,01 с | Тот же токен работает через 1,5 с после старта Valkey |
| `docker compose stop postgres` | Ограниченный 503 | Сначала 503 за 3,02 с, затем 503 от балансировщика за 0,01 с | Работает через 5,6 с после старта PostgreSQL |
## Ограничения и следующие шаги ## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. - **Один хост.** Отказ узла не выдерживается.
- **Единичные компоненты.** Балансировщик, PostgreSQL и Valkey — по одному экземпляру: это единые точки отказа. Защищён только слой API.
- **Запись в один чат.** Сообщения одного чата записываются строго по очереди (блокировка строки чата): это цена порядка истории и идемпотентности. На пропускную способность записи в один чат это ограничение, на разные чаты — нет.
- **Поочерёдное обновление** выполняется скриптом, а не встроенным механизмом: в Compose такого механизма нет.
- **Падение процесса.** При `docker kill` выполнявшиеся запросы получают ошибку 502; без потери данных их можно только повторить с тем же ключом, как делает нагрузочный клиент.
- **Отказ общего хранилища.** Балансировщик отвечает 503 на все запросы, включая регистрацию.
- **`X-Instance-Id` раскрывает короткий ID контейнера.** Для lab3 это удобно, в lab7 его нужно заменить случайным псевдонимом.
- **Без ограничений по нагрузке.** Ограничения частоты запросов и защиты от перебора паролей нет. Поток создаётся на каждое соединение.
- **Нет CI.** Job со сборкой стенда не добавлен: репозиторий размещён на GitFlic.
+138
View File
@@ -0,0 +1,138 @@
# Стенд lab3: HAProxy -> API x2 -> общие PostgreSQL и Valkey.
# Перед первым запуском: python scripts/init_secrets.py
# Запуск: docker compose up -d --build --wait (подробно — REPORT.md, раздел «Запуск из чистого clone»).
name: mtusi-lab3
x-app: &app
build:
context: .
args:
APP_VERSION: ${APP_VERSION:-lab3}
image: mtusi-messenger:lab3
# Имя остановленного контейнера встроенный DNS Docker пересылает внешнему серверу и ждёт ответа
# около 4 с (замерено в lab2). Ограничиваем ожидание DNS одной секундой.
dns_opt:
- timeout:1
- attempts:1
x-api-environment: &api-environment
APP_HOST: 0.0.0.0
APP_PORT: "8080"
APP_ENV: ${APP_ENV:-lab}
APP_LOG_LEVEL: ${APP_LOG_LEVEL:-INFO}
APP_SHUTDOWN_TIMEOUT: ${APP_SHUTDOWN_TIMEOUT:-8}
APP_DRAIN_DELAY: ${APP_DRAIN_DELAY:-3}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
DB_POOL_SIZE: ${DB_POOL_SIZE:-10}
# Пароли передаются файлами секретов, а не переменными окружения.
DATABASE_URL_FILE: /run/secrets/database_url
CACHE_URL_FILE: /run/secrets/cache_url
services:
# Единственная публичная точка входа. Проверяет /health/ready каждой реплики каждую секунду.
lb:
image: haproxy:3.4.5-trixie@sha256:76928c0d6b39bdd5f1c15d519cf48c47a6aa18c1dc552f7af1c146d2aa003c14
volumes:
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
ports:
- "127.0.0.1:${APP_PUBLISHED_PORT:-8080}:8080"
# Страница состояния HAProxy (UP/DOWN реплик), только для этой машины.
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404"
depends_on:
api:
condition: service_healthy
deploy:
resources:
limits: {cpus: "0.50", memory: 128M}
restart: unless-stopped
# Реплики API: без container_name и без опубликованных портов, доступ только через lb.
api:
<<: *app
environment: *api-environment
secrets: [database_url, cache_url]
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits: {cpus: "0.50", memory: 256M}
depends_on:
postgres:
condition: service_healthy
valkey:
condition: service_healthy
migrate:
condition: service_completed_successfully
stop_grace_period: 10s
restart: unless-stopped
# Одноразовый сервис: применяет миграции один раз до старта реплик и завершается.
migrate:
<<: *app
command: ["python", "-m", "messenger.migrate"]
environment:
DATABASE_URL_FILE: /run/secrets/database_url
secrets: [database_url]
depends_on:
postgres:
condition: service_healthy
deploy:
resources:
limits: {cpus: "0.50", memory: 128M}
restart: "no"
postgres:
image: postgres:18.6-trixie@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336
environment:
POSTGRES_DB: messenger
POSTGRES_USER: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets: [postgres_password]
volumes:
# С PostgreSQL 18 образ хранит данные в /var/lib/postgresql/18/docker: volume монтируется на уровень выше.
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD", "pg_isready", "--username=messenger", "--dbname=messenger"]
interval: 5s
timeout: 3s
retries: 10
start_period: 10s
deploy:
resources:
limits: {cpus: "1.00", memory: 512M}
restart: unless-stopped
valkey:
image: valkey/valkey:9.0.6-trixie@sha256:63346cb24a61221e76bdf41acce99b3968a9fa83d8122144deab45394b27b4f2
command: ["valkey-server", "/usr/local/etc/valkey/valkey.conf"]
secrets: [valkey_auth]
volumes:
- valkeydata:/data
- ./infra/valkey/valkey.conf:/usr/local/etc/valkey/valkey.conf:ro
healthcheck:
# Пароль берётся из того же файла секрета, что подключает valkey.conf.
test: ["CMD-SHELL", "valkey-cli --no-auth-warning -a \"$$(sed -n 's/^requirepass //p' /run/secrets/valkey_auth)\" ping | grep -q PONG"]
interval: 5s
timeout: 3s
retries: 10
start_period: 5s
deploy:
resources:
limits: {cpus: "0.50", memory: 256M}
restart: unless-stopped
volumes:
pgdata:
valkeydata:
# Файлы создаёт scripts/init_secrets.py; каталог secrets/ в .gitignore.
# Каждому сервису выдаются только нужные ему секреты; lb не получает ни одного.
secrets:
postgres_password:
file: ./secrets/postgres_password
database_url:
file: ./secrets/database_url
valkey_auth:
file: ./secrets/valkey_auth
cache_url:
file: ./secrets/cache_url
+94
View File
@@ -0,0 +1,94 @@
# Build and test from a fresh clone of the solution branch, separate compose project with new volumes.
# Date: 2026-10-07 22:32 UTC; host Windows 11, Docker Desktop; clone made with core.autocrlf=true (as on the author machine).
# COMPOSE_PROJECT_NAME=mtusi-lab3-clean, load balancer on 127.0.0.1:8090 (stats 8494): the main stand is not touched.
$ git clone --branch solution/bvt2304-chernikov <repo> clean3
[exit code 0]
$ git log --oneline -1
5ae5211 ЛР 3 — БВТ2304 — Черников
[exit code 0]
$ python scripts/init_secrets.py
created secrets/postgres_password
created secrets/valkey_password
written secrets/database_url, secrets/valkey_auth, secrets/cache_url
[exit code 0]
$ cp .env.example .env
$ docker compose up -d --build --wait
Container mtusi-lab3-clean-postgres-1 Healthy
Container mtusi-lab3-clean-postgres-1 Healthy
Container mtusi-lab3-clean-valkey-1 Healthy
Container mtusi-lab3-clean-migrate-1 Exited
Container mtusi-lab3-clean-api-1 Healthy
Container mtusi-lab3-clean-api-2 Healthy
Container mtusi-lab3-clean-valkey-1 Healthy
Container mtusi-lab3-clean-postgres-1 Healthy
Container mtusi-lab3-clean-lb-1 Healthy
Container mtusi-lab3-clean-migrate-1 Exited
Container mtusi-lab3-clean-api-1 Healthy
Container mtusi-lab3-clean-api-2 Healthy
[exit code 0]
$ docker compose ps
NAME STATUS PORTS
mtusi-lab3-clean-api-1 Up 6 seconds (healthy) 8080/tcp
mtusi-lab3-clean-api-2 Up 6 seconds (healthy) 8080/tcp
mtusi-lab3-clean-lb-1 Up 1 second 127.0.0.1:8090->8080/tcp, 127.0.0.1:8494->8404/tcp
mtusi-lab3-clean-postgres-1 Up 16 seconds (healthy) 5432/tcp
mtusi-lab3-clean-valkey-1 Up 16 seconds (healthy) 6379/tcp
[exit code 0]
$ docker compose logs --no-log-prefix migrate
INFO event=migration_applied version=0001_schema duration_ms=12
INFO event=migration_applied version=0002_messages_history_index duration_ms=4
INFO event=migration_applied version=0003_idempotency_keys duration_ms=5
INFO event=migrations_done applied_now=3 total=3
[exit code 0]
$ docker compose run --rm --no-deps migrate
INFO event=migrations_done applied_now=0 total=3
[exit code 0]
$ python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8090
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
[exit code 0]
$ BASE_URL=http://127.0.0.1:8090 python -X utf8 -m unittest discover -s student-tests
Ran 86 tests in 19.577s
OK
[exit code 0]
$ python -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --base-url http://127.0.0.1:8090
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 111, "failed_attempts": 0, "first_recovery_seconds": 4.432}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
[exit code 0]
$ docker compose ps -a (one api replica is stopped by the hook)
mtusi-lab3-clean-api-1 Up 49 seconds (healthy)
mtusi-lab3-clean-api-2 Exited (0) 11 seconds ago
[exit code 0]
$ docker compose up -d --wait (restore the replica)
Container mtusi-lab3-clean-api-2 Started
Container mtusi-lab3-clean-api-1 Healthy
Container mtusi-lab3-clean-api-2 Healthy
Container mtusi-lab3-clean-api-1 Healthy
Container mtusi-lab3-clean-api-2 Healthy
[exit code 0]
$ python -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://127.0.0.1:8090
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
[exit code 0]
$ docker compose down -v (removes only the mtusi-lab3-clean project and its volumes)
Volume mtusi-lab3-clean_pgdata Removed
Volume mtusi-lab3-clean_valkeydata Removed
[exit code 0]
# exit codes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
RESULT: PASS
+96
View File
@@ -0,0 +1,96 @@
# 2026-10-07 22:30:37 UTC, PostgreSQL 18.6 (Debian 18.6-1.pgdg13+2) on x86_64-pc-linux-gnu, compiled by gcc (Debian 14.2.0-19) 14.2.0, 64-bit
# target chat 0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae: 10000 messages; noise chat 8efe2cac-fee0-4974-b5a0-197ee563140a: 20000 messages
# inserted and analyzed in 1.0 s
messages total: 55175, in target chat: 10000
== 1. First page, middle page and last page: index range scan, no sort ==
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae' ORDER BY created_at, id LIMIT 51;
QUERY PLAN
------------------------------------------------------------------------------------------------------------
Limit (actual time=0.045..0.183 rows=51.00 loops=1)
Buffers: shared hit=54
-> Index Scan using messages_chat_history_idx on messages (actual time=0.042..0.174 rows=51.00 loops=1)
Index Cond: (chat_id = '0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae'::uuid)
Index Searches: 1
Buffers: shared hit=54
Planning:
Buffers: shared hit=144
Planning Time: 0.722 ms
Execution Time: 0.220 ms
(10 rows)
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae' AND (created_at, id) > ('2026-10-07 22:30:43.623934+00', 'c51eae37-23c0-412f-8b9e-233311a6374d') ORDER BY created_at, id LIMIT 51;
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.020..0.033 rows=51.00 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_chat_history_idx on messages (actual time=0.019..0.027 rows=51.00 loops=1)
Index Cond: ((chat_id = '0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae'::uuid) AND (ROW(created_at, id) > ROW('2026-10-07 22:30:43.623934+00'::timestamp with time zone, 'c51eae37-23c0-412f-8b9e-233311a6374d'::uuid)))
Index Searches: 1
Buffers: shared hit=5
Planning Time: 0.068 ms
Execution Time: 0.059 ms
(8 rows)
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae' AND (created_at, id) > ('2026-10-07 22:30:48.635476+00', '61827eb5-875e-47be-b232-4b344ab1b5df') ORDER BY created_at, id LIMIT 51;
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.031..0.039 rows=20.00 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_chat_history_idx on messages (actual time=0.030..0.036 rows=20.00 loops=1)
Index Cond: ((chat_id = '0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae'::uuid) AND (ROW(created_at, id) > ROW('2026-10-07 22:30:48.635476+00'::timestamp with time zone, '61827eb5-875e-47be-b232-4b344ab1b5df'::uuid)))
Index Searches: 1
Buffers: shared hit=5
Planning Time: 0.077 ms
Execution Time: 0.054 ms
(8 rows)
== 2. Generic plan of the parameterized query (how a prepared statement with $1..$4 runs) ==
SET plan_cache_mode = force_generic_plan;
SET
PREPARE history_page(uuid, timestamptz, uuid, int) AS
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4;
PREPARE
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) EXECUTE history_page('0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae', '2026-10-07 22:30:43.623934+00', 'c51eae37-23c0-412f-8b9e-233311a6374d', 51);
QUERY PLAN
------------------------------------------------------------------------------------------------------------
Limit (actual time=0.038..0.051 rows=51.00 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_chat_history_idx on messages (actual time=0.032..0.040 rows=51.00 loops=1)
Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3)))
Index Searches: 1
Buffers: shared hit=5
Planning:
Buffers: shared hit=141
Planning Time: 0.836 ms
Execution Time: 0.107 ms
(10 rows)
== 3. For comparison: the same middle page without the index (rolled back) ==
BEGIN;
BEGIN
DROP INDEX messages_chat_history_idx;
DROP INDEX
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae' AND (created_at, id) > ('2026-10-07 22:30:43.623934+00', 'c51eae37-23c0-412f-8b9e-233311a6374d') ORDER BY created_at, id LIMIT 51;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=6.627..6.638 rows=51.00 loops=1)
Buffers: shared hit=809
-> Sort (actual time=6.624..6.629 rows=51.00 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=809
-> Seq Scan on messages (actual time=3.200..6.151 rows=5000.00 loops=1)
Filter: ((chat_id = '0026e6c1-47d7-4b72-ae1b-a7d3c5a493ae'::uuid) AND (ROW(created_at, id) > ROW('2026-10-07 22:30:43.623934+00'::timestamp with time zone, 'c51eae37-23c0-412f-8b9e-233311a6374d'::uuid)))
Rows Removed by Filter: 50175
Buffers: shared hit=803
Planning:
Buffers: shared hit=108
Planning Time: 0.468 ms
Execution Time: 6.680 ms
(14 rows)
ROLLBACK;
ROLLBACK
index still exists: true
+301
View File
@@ -0,0 +1,301 @@
# 2026-10-07 22:25:25 UTC, python 3.14.7, win32
# docker 29.8.1
== Stack: replicas, pinned images, health, limits, published ports, secrets ==
$ docker compose ps -a --format table {{.Name}} {{.Image}} {{.Status}} {{.Ports}}
NAME IMAGE STATUS PORTS
mtusi-lab3-api-3 mtusi-messenger:lab3 Up 6 minutes (healthy) 8080/tcp
mtusi-lab3-api-4 mtusi-messenger:lab3 Up 6 minutes (healthy) 8080/tcp
mtusi-lab3-lb-1 haproxy:3.4.5-trixie@sha256:76928c0d6b39bdd5f1c15d519cf48c47a6aa18c1dc552f7af1c146d2aa003c14 Up 6 minutes 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
mtusi-lab3-migrate-1 sha256:c2a29f803684ad58f400a42d32e5c262fa44580101e65188ef92ca6015e17885 Exited (0) 6 minutes ago
mtusi-lab3-postgres-1 postgres:18.6-trixie@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336 Up 6 minutes (healthy) 5432/tcp
mtusi-lab3-valkey-1 valkey/valkey:9.0.6-trixie@sha256:63346cb24a61221e76bdf41acce99b3968a9fa83d8122144deab45394b27b4f2 Up 6 minutes (healthy) 6379/tcp
$ docker compose config --format json
=> PASS: third-party images are pinned by tag and digest (haproxy:3.4.5-trixie@sha256:76928c0d6b39bdd5f1c15d519cf48c47a6aa18c1dc552f7af1c146d2aa003c14, postgres:18.6-trixie@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336, valkey/valkey:9.0.6-trixie@sha256:63346cb24a61221e76bdf41acce99b3968a9fa83d8122144deab45394b27b4f2)
api replicas: mtusi-lab3-api-3 (68717763b8c6), mtusi-lab3-api-4 (7fc81857cf65)
=> PASS: at least two api replicas of one compose service, no container_name (mtusi-lab3-api-3, mtusi-lab3-api-4)
health: mtusi-lab3-api-3=healthy, mtusi-lab3-api-4=healthy, postgres=healthy, valkey=healthy
=> PASS: all api replicas, postgres and valkey are healthy
=> PASS: API processes do not run as root (mtusi-lab3-api-3 uid=10001, mtusi-lab3-api-4 uid=10001)
container cpus memory published ports
lb 0.50 128 MB 127.0.0.1:8080->8080/tcp 127.0.0.1:8404->8404/tcp
mtusi-lab3-api-3 0.50 256 MB -
mtusi-lab3-api-4 0.50 256 MB -
postgres 1.00 512 MB -
valkey 0.50 256 MB -
=> PASS: every container has CPU and memory limits
=> PASS: only the load balancer publishes ports, and only on 127.0.0.1
secrets per service: api=cache_url,database_url; lb=-; migrate=database_url; postgres=postgres_password; valkey=valkey_auth
=> PASS: secrets are given only where needed
$ docker compose exec -T valkey sh -c valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_auth)" CONFIG GET appendonly
appendonly
yes
$ docker compose exec -T valkey sh -c valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_auth)" CONFIG GET appendfsync
appendfsync
always
$ docker compose exec -T valkey sh -c valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_auth)" CONFIG GET maxmemory-policy
maxmemory-policy
noeviction
=> PASS: Valkey persistence is AOF with fsync always, no eviction
== Migrations: run once by the migrate service, idempotent re-run ==
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT version || ' ' || applied_at FROM schema_migrations ORDER BY version
0001_schema 2026-10-07 22:03:12.021632+00
0002_messages_history_index 2026-10-07 22:03:12.034748+00
0003_idempotency_keys 2026-10-07 22:03:12.038316+00
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT format('%s %s %s', conrelid::regclass, contype, conname) FROM pg_constraint WHERE conrelid::regclass::text = 'idempotency_keys' ORDER BY 1
idempotency_keys c idempotency_keys_key_format
idempotency_keys f idempotency_keys_message_id_fkey
idempotency_keys f idempotency_keys_user_id_fkey
idempotency_keys n idempotency_keys_created_at_not_null
idempotency_keys n idempotency_keys_key_not_null
idempotency_keys n idempotency_keys_message_id_not_null
idempotency_keys n idempotency_keys_method_not_null
idempotency_keys n idempotency_keys_path_not_null
idempotency_keys n idempotency_keys_request_hash_not_null
idempotency_keys n idempotency_keys_user_id_not_null
idempotency_keys p idempotency_keys_pkey
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT (SELECT count(*) FROM schema_migrations) || ' ' || (SELECT count(*) FROM users)
3 205
$ docker compose run --rm --no-deps migrate
Container mtusi-lab3-migrate-run-ee50296698bb Creating
Container mtusi-lab3-migrate-run-ee50296698bb Created
INFO event=migrations_done applied_now=0 total=3
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT (SELECT count(*) FROM schema_migrations) || ' ' || (SELECT count(*) FROM users)
3 205
schema_migrations and users rows before/after: 3 205 / 3 205
=> PASS: re-running migrations applies nothing and duplicates nothing
== Balancing: one session, many replicas ==
X-Instance-Id 68717763b8c6 (mtusi-lab3-api-3): 20 responses with status 200
X-Instance-Id 7fc81857cf65 (mtusi-lab3-api-4): 20 responses with status 200
=> PASS: 40 requests with one token are served by every replica without a new login
== Idempotency: 20 parallel POSTs with one key through the load balancer ==
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT count(*) FROM messages WHERE chat_id = '83406a9f-af29-4189-bd5a-80f48d1d064f'
1
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT count(*) FROM idempotency_keys WHERE key = '8eaaba5dfe6645a895251432314215c9'
1
statuses: [201]; distinct message ids: 1; replicas that answered: 68717763b8c6, 7fc81857cf65
messages in the chat: 1; idempotency_keys rows for the key: 1
same key, another body -> 409 conflict in 0.01 s, X-Instance-Id 7fc81857cf65
=> PASS: one message for 20 concurrent requests with one key on several replicas
=> PASS: the same key with another body is rejected with 409
== Rollback: chat creation fails on the second INSERT ==
POST /api/v1/chats with one unknown member -> 400 invalid_request in 0.02 s, X-Instance-Id 68717763b8c6
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT count(*) FROM chats WHERE title = 'rollback-probe-197e464657'
0
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT count(*) FROM chats c WHERE NOT EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)
0
rows in chats with this title: 0; chats without members: 0
=> PASS: composite chat creation is rolled back as a whole
== Registration race: 20 parallel requests with one username ==
statuses: 201 409 409 409 409 409 409 409 409 409 409 409 409 409 409 409 409 409 409 409; replicas: 68717763b8c6, 7fc81857cf65
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c SELECT count(*) FROM users WHERE username = 'race_9ef48474bc80'
1
rows in users with this username: 1
=> PASS: exactly one registration wins, the other 19 get 409
== Connection pools: 60 parallel clients, at most 10 connections per replica (2 replicas) ==
requests: 563, statuses: {200: 563}
API connections in pg_stat_activity, 9 samples: max 20
=> PASS: pools never open more than 10 connections per replica and all requests succeed
== Timeouts: chat row locked for 6 s by another session, API answers 503 after lock_timeout=3s ==
$ docker compose exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 -At -c "BEGIN; SELECT 1 FROM chats WHERE id = '6026c0e8-0d1a-4e86-ae54-da84dc874367' FOR UPDATE; SELECT pg_sleep(6); ROLLBACK;" (in the background)
POST message while the chat row is locked -> 503 unavailable in 3.02 s, X-Instance-Id 68717763b8c6
POST message after the lock is released -> 201 in 0.02 s, X-Instance-Id 7fc81857cf65
=> PASS: waiting for a lock is bounded: 503 after about 3 s, then writes work again (3.02 s)
== Logs: useful fields, no message texts, passwords or tokens (all api replicas and lb) ==
$ docker compose logs --no-log-prefix api lb
$ docker compose logs --tail 2 api
api-3 | 2026-10-07T22:25:54.557Z INFO request_id=966a547d1ac94f6c82eff4c595ee9f9b method=POST path=/api/v1/chats status=201 duration_ms=5.8 user_id=44136183-c19b-4b5a-adbb-6858489b0330
api-4 | 2026-10-07T22:25:54.437Z INFO request_id=964da93e470f47caa94279cd2e9e7516 method=POST path=/api/v1/chats/6026c0e8-0d1a-4e86-ae54-da84dc874367/messages status=201 duration_ms=12.0 user_id=ac7c4c7a-41aa-401d-bdd5-39d27066e9b3
api-4 | 2026-10-07T22:25:54.543Z INFO request_id=23d18bd6174749a99f9fb1dd222bdfb7 method=POST path=/api/v1/auth/sessions status=201 duration_ms=39.0 user_id=44136183-c19b-4b5a-adbb-6858489b0330
api-3 | 2026-10-07T22:25:54.583Z INFO request_id=61b9245ffbf24e6ea1d5c0e46ddd1e80 method=POST path=/api/v1/chats/2bdbc8f5-9be8-449d-940b-5c97ef9a6943/messages status=201 duration_ms=10.7 user_id=44136183-c19b-4b5a-adbb-6858489b0330
$ docker compose logs --no-log-prefix --tail 2 lb
172.19.0.1:57694 [07/Oct/2026:22:25:54.549] public api/api1 0/0/1/6/7 201 373 - - ---- 1/1/0/0/0 0/0 "POST /api/v1/chats HTTP/1.1"
172.19.0.1:57710 [07/Oct/2026:22:25:54.570] public api/api1 0/0/0/13/13 201 457 - - ---- 1/1/0/0/0 0/0 "POST /api/v1/chats/2bdbc8f5-9be8-449d-940b-5c97ef9a6943/messages HTTP/1.1"
searched 41389 log lines; found: nothing
=> PASS: logs contain request_id/status/duration and no secrets
== Session expiry: api replicas recreated with SESSION_TTL_SECONDS=2, then restored ==
$ docker compose up -d --no-deps --wait api
GET /users/me right after login -> 200 in 0.01 s, X-Instance-Id 911800b97ae9
$ docker compose exec -T valkey sh -c valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_auth)" PTTL session:6b03ee75d9f79c514394462e72c39c21a3d11ace901c5a42c89b5ef93cd136fb
1694
PTTL of the session key in Valkey (ms): 1694
GET /users/me 3 s later -> 401 unauthorized in 0.02 s, X-Instance-Id ba820ebd9c68
$ docker compose exec -T valkey sh -c valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_auth)" EXISTS session:6b03ee75d9f79c514394462e72c39c21a3d11ace901c5a42c89b5ef93cd136fb
0
session key still exists in Valkey: 0
=> PASS: session expires after SESSION_TTL_SECONDS and the key disappears from Valkey
$ docker compose up -d --no-deps --wait api
== Valkey is down ==
$ docker compose stop valkey
Container mtusi-lab3-valkey-1 Stopping
Container mtusi-lab3-valkey-1 Stopped
GET /users/me with a valid token (first seconds) -> 503 unavailable in 1.02 s, X-Instance-Id 34f46eb4cd91
GET /users/me with a valid token (after 3 s) -> 503 unavailable in 0.01 s, X-Instance-Id -
GET /users/me without a token -> 503 unavailable in 0.01 s, X-Instance-Id -
GET /health/ready -> 503 unavailable in 0.00 s, X-Instance-Id -
slowest of 3 more authenticated requests: 0.01 s
$ docker compose start valkey
Container mtusi-lab3-valkey-1 Starting
Container mtusi-lab3-valkey-1 Started
same token after valkey is back: 200 after 1.5 s
=> PASS: without valkey: bounded 503, nothing is served as anonymous
=> PASS: the stand recovers by itself when valkey is back, the session is still valid
== PostgreSQL is down ==
$ docker compose stop postgres
Container mtusi-lab3-postgres-1 Stopping
Container mtusi-lab3-postgres-1 Stopped
GET /users/me with a valid token (first seconds) -> 503 unavailable in 3.02 s, X-Instance-Id cc69293773ec
GET /users/me with a valid token (after 3 s) -> 503 unavailable in 0.01 s, X-Instance-Id -
GET /users/me without a token -> 503 unavailable in 0.01 s, X-Instance-Id -
GET /health/ready -> 503 unavailable in 0.01 s, X-Instance-Id -
slowest of 3 more authenticated requests: 0.01 s
$ docker compose start postgres
Container mtusi-lab3-postgres-1 Starting
Container mtusi-lab3-postgres-1 Started
same token after postgres is back: 200 after 5.6 s
=> PASS: without postgres: bounded 503, nothing is served as anonymous
=> PASS: the stand recovers by itself when postgres is back, the session is still valid
== Public failover test: tests/resilience.py --mode failover, repeated until every replica was the target ==
$ C:\Users\Dima Chernikov\AppData\Local\Programs\Python\Python314\python.exe -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --base-url http://127.0.0.1:8080
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 112, "failed_attempts": 0, "first_recovery_seconds": 3.827}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
attempt 1: stopped container cc69293773ec (mtusi-lab3-api-4), State: exited, ExitCode 0
=> PASS: public failover test passes (attempt 1) (17.1 s)
$ docker compose up -d --wait
$ C:\Users\Dima Chernikov\AppData\Local\Programs\Python\Python314\python.exe -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --base-url http://127.0.0.1:8080
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 106, "failed_attempts": 0, "first_recovery_seconds": 4.132}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
attempt 2: stopped container 34f46eb4cd91 (mtusi-lab3-api-3), State: exited, ExitCode 0
=> PASS: public failover test passes (attempt 2) (16.7 s)
$ docker compose up -d --wait
=> PASS: every replica was stopped by the hook at least once (mtusi-lab3-api-3, mtusi-lab3-api-4)
== Experiment: stop, then kill, each replica in turn under load; restore before the next one ==
$ docker stop 34f46eb4cd91
$ docker start 34f46eb4cd91
{"replica": "mtusi-lab3-api-3", "lb_slot": "api2", "action": "docker stop", "command_s": 3.93, "baseline_ok_rps": 148.2, "during_ok_rps": 81.3, "errors_during": 0, "requests_during": 970, "max_gap_s": 0.18, "lb_marked_down_s": 1.0, "last_served_s": 0.97, "back_in_rotation_s": 5.19, "after_ok_rps": 218.1, "errors_after": 0}
$ docker stop cc69293773ec
$ docker start cc69293773ec
{"replica": "mtusi-lab3-api-4", "lb_slot": "api1", "action": "docker stop", "command_s": 3.96, "baseline_ok_rps": 171.4, "during_ok_rps": 83.8, "errors_during": 0, "requests_during": 1002, "max_gap_s": 0.1, "lb_marked_down_s": 1.09, "last_served_s": 1.02, "back_in_rotation_s": 5.34, "after_ok_rps": 165.3, "errors_after": 0}
$ docker kill 34f46eb4cd91
$ docker start 34f46eb4cd91
{"replica": "mtusi-lab3-api-3", "lb_slot": "api2", "action": "docker kill", "command_s": 0.4, "baseline_ok_rps": 202.0, "during_ok_rps": 69.4, "errors_during": 2, "requests_during": 585, "max_gap_s": 0.93, "lb_marked_down_s": 0.47, "last_served_s": 0.1, "back_in_rotation_s": 5.47, "after_ok_rps": 123.8, "errors_after": 0}
$ docker kill cc69293773ec
$ docker start cc69293773ec
{"replica": "mtusi-lab3-api-4", "lb_slot": "api1", "action": "docker kill", "command_s": 0.43, "baseline_ok_rps": 151.4, "during_ok_rps": 67.6, "errors_during": 3, "requests_during": 573, "max_gap_s": 0.98, "lb_marked_down_s": 0.42, "last_served_s": 0.07, "back_in_rotation_s": 5.49, "after_ok_rps": 156.2, "errors_after": 0}
replica action cmd,s rps0 rps errors gap,s down,s back,s rps1
mtusi-lab3-api-3 docker stop 3.93 148.2 81.3 0 0.18 1.0 5.19 218.1
mtusi-lab3-api-4 docker stop 3.96 171.4 83.8 0 0.1 1.09 5.34 165.3
mtusi-lab3-api-3 docker kill 0.4 202.0 69.4 2 0.93 0.47 5.47 123.8
mtusi-lab3-api-4 docker kill 0.43 151.4 67.6 3 0.98 0.42 5.49 156.2
acknowledged writes: 4858, found in history: 4858, duplicates: 0
=> PASS: graceful stop of each replica: no client errors, LB removes it within 3 s
=> PASS: kill of each replica: LB removes it within 3 s, writes go on within 10 s
=> PASS: every replica comes back into rotation after docker start
=> PASS: no acknowledged write is lost or duplicated (retries reuse the key)
== Rolling update under load: one replica at a time, new image, migrations once ==
$ docker compose build api
image before 4f0ecfa64963, after e85c788ea2be, APP_VERSION=rolling-1791412151
$ docker compose run --rm --no-deps migrate
Container mtusi-lab3-migrate-run-132d5c300c9b Creating
Container mtusi-lab3-migrate-run-132d5c300c9b Created
INFO event=migrations_done applied_now=0 total=3
$ docker compose up -d --no-deps --no-recreate --scale api=3 api
$ docker stop 34f46eb4cd91
$ docker rm 34f46eb4cd91
replaced mtusi-lab3-api-3 (34f46eb4cd91) -> 27757842cabd
$ docker compose up -d --no-deps --no-recreate --scale api=3 api
$ docker stop cc69293773ec
$ docker rm cc69293773ec
replaced mtusi-lab3-api-4 (cc69293773ec) -> 45ad15a9929a
during the update: {"requests": 5582, "ok": 5582, "errors": 0, "ok_rps": 190.1}
final replicas: mtusi-lab3-api-5 27757842cabd version=rolling-1791412151, mtusi-lab3-api-6 45ad15a9929a version=rolling-1791412151
acknowledged writes: 2791, found in history: 2791, duplicates: 0
=> PASS: migrations are applied once and the change is backward compatible
=> PASS: every replica was replaced one by one by the new image under load
=> PASS: no client errors and no lost or duplicated writes during the rolling update (5582 requests, 190.1 ok RPS)
== Full restart: public tests/resilience.py --mode persistence with the restart hook ==
$ docker volume inspect -f {{.Name}} {{.CreatedAt}} mtusi-lab3_pgdata mtusi-lab3_valkeydata
mtusi-lab3_pgdata 2026-10-07T22:03:02Z
mtusi-lab3_valkeydata 2026-10-07T22:03:02Z
$ C:\Users\Dima Chernikov\AppData\Local\Programs\Python\Python314\python.exe -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://127.0.0.1:8080
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.␍
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
$ docker volume inspect -f {{.Name}} {{.CreatedAt}} mtusi-lab3_pgdata mtusi-lab3_valkeydata
mtusi-lab3_pgdata 2026-10-07T22:03:02Z
mtusi-lab3_valkeydata 2026-10-07T22:03:02Z
lb StartedAt 22:19:18.913 -> 22:30:10.030
mtusi-lab3-api-5 StartedAt 22:29:22.591 -> 22:30:06.409
mtusi-lab3-api-6 StartedAt 22:29:34.442 -> 22:30:06.102
postgres StartedAt 22:26:35.615 -> 22:29:56.621
valkey StartedAt 22:26:26.521 -> 22:29:56.526
=> PASS: persistence test passes after restarting every replica, postgres, valkey and lb with the same volumes (hook scripts/restart.cmd, 19.9 s)
== Summary ==
PASS third-party images are pinned by tag and digest
PASS at least two api replicas of one compose service, no container_name
PASS all api replicas, postgres and valkey are healthy
PASS API processes do not run as root
PASS every container has CPU and memory limits
PASS only the load balancer publishes ports, and only on 127.0.0.1
PASS secrets are given only where needed
PASS Valkey persistence is AOF with fsync always, no eviction
PASS re-running migrations applies nothing and duplicates nothing
PASS 40 requests with one token are served by every replica without a new login
PASS one message for 20 concurrent requests with one key on several replicas
PASS the same key with another body is rejected with 409
PASS composite chat creation is rolled back as a whole
PASS exactly one registration wins, the other 19 get 409
PASS pools never open more than 10 connections per replica and all requests succeed
PASS waiting for a lock is bounded: 503 after about 3 s, then writes work again
PASS logs contain request_id/status/duration and no secrets
PASS session expires after SESSION_TTL_SECONDS and the key disappears from Valkey
PASS without valkey: bounded 503, nothing is served as anonymous
PASS the stand recovers by itself when valkey is back, the session is still valid
PASS without postgres: bounded 503, nothing is served as anonymous
PASS the stand recovers by itself when postgres is back, the session is still valid
PASS public failover test passes (attempt 1)
PASS public failover test passes (attempt 2)
PASS every replica was stopped by the hook at least once
PASS graceful stop of each replica: no client errors, LB removes it within 3 s
PASS kill of each replica: LB removes it within 3 s, writes go on within 10 s
PASS every replica comes back into rotation after docker start
PASS no acknowledged write is lost or duplicated (retries reuse the key)
PASS migrations are applied once and the change is backward compatible
PASS every replica was replaced one by one by the new image under load
PASS no client errors and no lost or duplicated writes during the rolling update
PASS persistence test passes after restarting every replica, postgres, valkey and lb with the same volumes
RESULT: PASS
+19
View File
@@ -0,0 +1,19 @@
{
"base_url": "http://127.0.0.1:8080",
"clients": 10,
"messages_per_client": 10,
"sent": 100,
"accepted_201": 100,
"history_total": 100,
"history_unique_ids": 100,
"history_unique_texts": 100,
"history_matches_accepted": true,
"senders_in_history": 10,
"min_messages_per_sender": 10,
"max_messages_per_sender": 10,
"ordered_by_created_at_and_id": true,
"pages_read": 15,
"page_size": 7,
"send_elapsed_seconds": 0.647,
"ok": true
}
+132
View File
@@ -0,0 +1,132 @@
# Tests through the load balancer of the compose stand (docker compose up -d --build --wait), 2 API replicas.
# Date: 2026-10-07 22:24 UTC
# Host: Windows 11, Docker Desktop engine 29.8.1, Compose 5.5.1, Python 3.14.7 for the test clients;
# Intel Core Ultra 9 185H (16 cores, 22 threads), 31 GiB RAM, no CPU/RAM limits on containers.
# Code: working tree of the solution branch (commit is given in REPORT.md).
$ python -X utf8 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
[exit code 0]
$ python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8080
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
[exit code 0]
$ BASE_URL=http://127.0.0.1:8080 python -X utf8 -m unittest discover -s student-tests -v
test_authentication_is_checked_before_body_and_resource (test_access.AuthenticationOrderTest.test_authentication_is_checked_before_body_and_resource) ... ok
test_registration_does_not_need_a_token (test_access.AuthenticationOrderTest.test_registration_does_not_need_a_token) ... ok
test_chat_list_contains_only_own_chats (test_access.ForeignChatTest.test_chat_list_contains_only_own_chats) ... ok
test_every_member_can_read_and_write (test_access.ForeignChatTest.test_every_member_can_read_and_write) ... ok
test_foreign_chat_looks_like_missing_chat (test_access.ForeignChatTest.test_foreign_chat_looks_like_missing_chat) ... ok
test_invalid_chat_id_is_400 (test_access.ForeignChatTest.test_invalid_chat_id_is_400) ... ok
test_outsider_cannot_get_chat (test_access.ForeignChatTest.test_outsider_cannot_get_chat) ... ok
test_outsider_cannot_read_history (test_access.ForeignChatTest.test_outsider_cannot_read_history) ... ok
test_outsider_cannot_write (test_access.ForeignChatTest.test_outsider_cannot_write) ... ok
test_unknown_route_is_404 (test_access.ForeignChatTest.test_unknown_route_is_404) ... ok
test_x_user_id_does_not_open_a_foreign_chat (test_access.ForeignChatTest.test_x_user_id_does_not_open_a_foreign_chat) ... ok
test_errors_also_carry_instance_id (test_balancing.BalancingTest.test_errors_also_carry_instance_id) ... ok
test_message_written_on_one_replica_is_read_on_another (test_balancing.BalancingTest.test_message_written_on_one_replica_is_read_on_another) ... ok
test_one_session_is_served_by_several_replicas (test_balancing.BalancingTest.test_one_session_is_served_by_several_replicas) ... ok
test_100_messages_from_10_clients (test_concurrency.ConcurrencyTest.test_100_messages_from_10_clients) ... ok
test_chats_created_in_parallel_are_all_listed (test_concurrency.ConcurrencyTest.test_chats_created_in_parallel_are_all_listed) ... ok
test_same_username_registered_in_parallel_wins_once (test_concurrency.ConcurrencyTest.test_same_username_registered_in_parallel_wins_once) ... ok
test_failed_validation_is_not_remembered (test_idempotency.IdempotencyTest.test_failed_validation_is_not_remembered) ... ok
test_invalid_keys_are_400 (test_idempotency.IdempotencyTest.test_invalid_keys_are_400) ... ok
test_json_formatting_does_not_matter (test_idempotency.IdempotencyTest.test_json_formatting_does_not_matter) ... ok
test_key_format_limits_are_accepted (test_idempotency.IdempotencyTest.test_key_format_limits_are_accepted) ... ok
test_key_scope_is_user_and_chat (test_idempotency.IdempotencyTest.test_key_scope_is_user_and_chat) ... ok
test_missing_key_is_400 (test_idempotency.IdempotencyTest.test_missing_key_is_400) ... ok
test_parallel_requests_with_one_key_create_one_message (test_idempotency.IdempotencyTest.test_parallel_requests_with_one_key_create_one_message) ... ok
test_replay_checks_the_session_again (test_idempotency.IdempotencyTest.test_replay_checks_the_session_again) ... ok
test_replay_returns_the_same_message (test_idempotency.IdempotencyTest.test_replay_returns_the_same_message) ... ok
test_same_key_with_another_body_is_409 (test_idempotency.IdempotencyTest.test_same_key_with_another_body_is_409) ... ok
test_chats_are_paged_in_creation_order (test_pagination.ChatListPaginationTest.test_chats_are_paged_in_creation_order) ... ok
test_cursor_of_another_user_is_400 (test_pagination.ChatListPaginationTest.test_cursor_of_another_user_is_400) ... ok
test_default_limit_is_50 (test_pagination.DefaultLimitTest.test_default_limit_is_50) ... ok
test_empty_history (test_pagination.GrowingHistoryTest.test_empty_history) ... ok
test_messages_sent_during_walk_are_not_lost (test_pagination.GrowingHistoryTest.test_messages_sent_during_walk_are_not_lost) ... ok
test_cursor_from_another_chat_is_400 (test_pagination.MessagePaginationTest.test_cursor_from_another_chat_is_400) ... ok
test_default_and_maximum_limit (test_pagination.MessagePaginationTest.test_default_and_maximum_limit) ... ok
test_invalid_cursor_is_400 (test_pagination.MessagePaginationTest.test_invalid_cursor_is_400) ... ok
test_invalid_limit_is_400 (test_pagination.MessagePaginationTest.test_invalid_limit_is_400) ... ok
test_last_full_page_has_no_cursor (test_pagination.MessagePaginationTest.test_last_full_page_has_no_cursor) ... ok
test_limit_can_change_between_pages (test_pagination.MessagePaginationTest.test_limit_can_change_between_pages) ... ok
test_one_message_per_page (test_pagination.MessagePaginationTest.test_one_message_per_page) ... ok
test_walk_over_several_pages (test_pagination.MessagePaginationTest.test_walk_over_several_pages) ... ok
test_basic_is_rejected_on_business_endpoints (test_sessions.BearerTest.test_basic_is_rejected_on_business_endpoints) ... ok
test_protected_endpoints_need_a_token (test_sessions.BearerTest.test_protected_endpoints_need_a_token) ... ok
test_scheme_name_is_case_insensitive (test_sessions.BearerTest.test_scheme_name_is_case_insensitive) ... ok
test_token_selects_the_user (test_sessions.BearerTest.test_token_selects_the_user) ... ok
test_unknown_or_malformed_token (test_sessions.BearerTest.test_unknown_or_malformed_token) ... ok
test_x_user_id_is_ignored (test_sessions.BearerTest.test_x_user_id_is_ignored) ... ok
test_credentials_in_json_body_are_not_accepted (test_sessions.LoginTest.test_credentials_in_json_body_are_not_accepted) ... ok
test_each_login_gives_a_new_token (test_sessions.LoginTest.test_each_login_gives_a_new_token) ... ok
test_malformed_basic_header (test_sessions.LoginTest.test_malformed_basic_header) ... ok
test_password_with_colons_and_unicode (test_sessions.LoginTest.test_password_with_colons_and_unicode) ... ok
test_registration_never_returns_password (test_sessions.LoginTest.test_registration_never_returns_password) ... ok
test_successful_login (test_sessions.LoginTest.test_successful_login) ... ok
test_unknown_user_gets_the_same_answer (test_sessions.LoginTest.test_unknown_user_gets_the_same_answer) ... ok
test_wrong_password (test_sessions.LoginTest.test_wrong_password) ... ok
test_login_again_after_logout (test_sessions.LogoutTest.test_login_again_after_logout) ... ok
test_logout_revokes_only_the_current_token (test_sessions.LogoutTest.test_logout_revokes_only_the_current_token) ... ok
test_bad_member_ids (test_validation.ChatValidationTest.test_bad_member_ids) ... ok
test_bad_titles (test_validation.ChatValidationTest.test_bad_titles) ... ok
test_caller_must_be_a_member (test_validation.ChatValidationTest.test_caller_must_be_a_member) ... ok
test_duplicate_members (test_validation.ChatValidationTest.test_duplicate_members) ... ok
test_unknown_member_rolls_back_the_whole_chat (test_validation.ChatValidationTest.test_unknown_member_rolls_back_the_whole_chat) ... ok
test_valid_chat_keeps_member_order (test_validation.ChatValidationTest.test_valid_chat_keeps_member_order) ... ok
test_extra_fields (test_validation.InvalidJsonTest.test_extra_fields) ... ok
test_invalid_utf8 (test_validation.InvalidJsonTest.test_invalid_utf8) ... ok
test_json_that_is_not_an_object (test_validation.InvalidJsonTest.test_json_that_is_not_an_object) ... ok
test_lone_surrogate_is_rejected_not_crashed (test_validation.InvalidJsonTest.test_lone_surrogate_is_rejected_not_crashed) ... ok
test_malformed_json_on_message (test_validation.InvalidJsonTest.test_malformed_json_on_message) ... ok
test_malformed_json_on_register (test_validation.InvalidJsonTest.test_malformed_json_on_register) ... ok
test_nul_character_is_rejected_not_crashed (test_validation.InvalidJsonTest.test_nul_character_is_rejected_not_crashed) ... ok
test_wrong_content_type (test_validation.InvalidJsonTest.test_wrong_content_type) ... ok
test_wrong_types (test_validation.InvalidJsonTest.test_wrong_types) ... ok
test_empty_message_is_400 (test_validation.MessageValidationTest.test_empty_message_is_400) ... ok
test_missing_or_wrong_text (test_validation.MessageValidationTest.test_missing_or_wrong_text) ... ok
test_nul_in_text_is_400 (test_validation.MessageValidationTest.test_nul_in_text_is_400) ... ok
test_oversized_body_is_413 (test_validation.MessageValidationTest.test_oversized_body_is_413) ... ok
test_sender_id_in_body_is_rejected (test_validation.MessageValidationTest.test_sender_id_in_body_is_rejected) ... ok
test_text_length_limit (test_validation.MessageValidationTest.test_text_length_limit) ... ok
test_unicode_text_is_kept (test_validation.MessageValidationTest.test_unicode_text_is_kept) ... ok
test_bad_display_names (test_validation.UserValidationTest.test_bad_display_names) ... ok
test_bad_passwords (test_validation.UserValidationTest.test_bad_passwords) ... ok
test_bad_usernames (test_validation.UserValidationTest.test_bad_usernames) ... ok
test_duplicate_username_is_409 (test_validation.UserValidationTest.test_duplicate_username_is_409) ... ok
test_missing_fields (test_validation.UserValidationTest.test_missing_fields) ... ok
test_password_length_limits_are_accepted (test_validation.UserValidationTest.test_password_length_limits_are_accepted) ... ok
test_unicode_display_name_is_kept (test_validation.UserValidationTest.test_unicode_display_name_is_kept) ... ok
test_username_length_limits_are_accepted (test_validation.UserValidationTest.test_username_length_limits_are_accepted) ... ok
----------------------------------------------------------------------
Ran 86 tests in 18.104s
OK
[exit code 0]
$ BASE_URL=http://127.0.0.1:8080 python student-tests/race.py --output evidence/race.json
{
"base_url": "http://127.0.0.1:8080",
"clients": 10,
"messages_per_client": 10,
"sent": 100,
"accepted_201": 100,
"history_total": 100,
"history_unique_ids": 100,
"history_unique_texts": 100,
"history_matches_accepted": true,
"senders_in_history": 10,
"min_messages_per_sender": 10,
"max_messages_per_sender": 10,
"ordered_by_created_at_and_id": true,
"pages_read": 15,
"page_size": 7,
"send_elapsed_seconds": 0.647,
"ok": true
}
PASS
[exit code 0]
# exit codes: [0, 0, 0, 0]
+72
View File
@@ -0,0 +1,72 @@
# HAProxy для lab3: единая точка входа, round-robin между репликами API.
# Реплики находятся через DNS Docker и исключаются по активной проверке /health/ready.
global
log stdout format raw local0 info
maxconn 4096
# Встроенный DNS Docker: имя сервиса api возвращает адреса всех запущенных реплик.
# Список перечитывается каждую секунду, поэтому новые и удалённые реплики видны сразу.
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold obsolete 1s
hold other 1s
hold refused 1s
hold nx 1s
hold timeout 1s
accepted_payload_size 8192
defaults
mode http
log global
option httplog
option dontlognull
# Соединение к реплике закрывается после каждого ответа: запрос не уйдёт по старому
# соединению в реплику, которая уже закрывает приём.
option http-server-close
timeout connect 1s
timeout client 30s
timeout server 15s
timeout http-request 10s
timeout http-keep-alive 10s
timeout check 1s
# Повтор только если соединение с репликой не установилось: запрос до неё не дошёл,
# поэтому повтор на другой реплике безопасен даже для POST.
retries 2
retry-on conn-failure
option redispatch 1
# Ошибки самого балансировщика — в формате ошибок контракта (без X-Instance-Id: его ставит только API).
unique-id-format %[uuid()]
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"API replica failed to respond","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"No API replica is available","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"API replica did not answer in time","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
frontend public
bind :8080
default_backend api
backend api
balance roundrobin
# Реплика готова, только пока /health/ready отвечает 200. После SIGTERM реплика сама
# начинает отвечать 503 и ещё 3 с обслуживает запросы (APP_DRAIN_DELAY).
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
# inter 1s: проверка раз в секунду; после первой неудачи — раз в 0,5 с (fastinter);
# fall 2: реплика исключается после двух неудач подряд, то есть примерно за 1,5–2,5 с.
# rise 2: возвращается после двух успешных проверок.
default-server check inter 1s fastinter 500ms downinter 2s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
server-template api 1-8 api:8080
# Страница состояния: какие реплики UP/DOWN. Опубликована только на 127.0.0.1.
frontend stats
bind :8404
stats enable
stats uri /
stats refresh 2s
# Показывать адреса реплик: по ним видно, какой контейнер в каком состоянии.
stats show-legends
+23
View File
@@ -0,0 +1,23 @@
# Valkey для сессий lab2. Это единственное хранилище сессий, поэтому включена persistence.
# Пароль (строка requirepass ...) лежит в файле секрета, который создаёт scripts/init_secrets.py.
include /run/secrets/valkey_auth
bind 0.0.0.0
port 6379
protected-mode yes
dir /data
# AOF: каждая запись попадает в журнал на диске, и после рестарта Valkey восстанавливает его.
# fsync на каждую запись: сессия подтверждается клиенту только после записи на диск.
# Записей мало (только вход и выход), поэтому цена fsync незаметна.
appendonly yes
appendfsync always
# RDB-снимки не нужны: всё восстанавливается из AOF.
save ""
# Сессии нельзя вытеснять молча: при нехватке памяти новая запись получит ошибку,
# и API ответит 503, а уже выданные сессии останутся.
maxmemory 128mb
maxmemory-policy noeviction
+46
View File
@@ -0,0 +1,46 @@
-- Схема мессенджера: пользователи, чаты, участники, сообщения.
-- Ограничения повторяют правила контракта, чтобы база не приняла неверные данные,
-- даже если ошибка будет в коде приложения.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL, -- Argon2id, сам пароль не хранится
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100)
);
-- Участники задаются при создании чата и потом не меняются.
-- position хранит порядок member_ids из запроса на создание.
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id),
user_id uuid NOT NULL REFERENCES users (id),
position smallint NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_key UNIQUE (chat_id, position)
);
-- Список чатов пользователя ищется по user_id.
CREATE INDEX chat_members_user_id_idx ON chat_members (user_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000),
-- Отправитель обязан состоять в чате: это проверяет и база, а не только код.
CONSTRAINT messages_sender_is_member FOREIGN KEY (chat_id, sender_id)
REFERENCES chat_members (chat_id, user_id)
);
@@ -0,0 +1,8 @@
-- Индекс для чтения истории чата. Приложение выполняет запрос
-- SELECT ... FROM messages
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4
-- Колонки индекса идут в том же порядке, поэтому страница читается диапазоном индекса
-- без сортировки и без просмотра всей истории чата. План на 10 000+ сообщениях —
-- в evidence/explain.txt (scripts/explain_history.py).
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
+20
View File
@@ -0,0 +1,20 @@
-- Идемпотентность отправки сообщения (с lab3).
-- Область ключа: пользователь + метод + путь чата + значение Idempotency-Key.
-- Строка ключа и сообщение создаются в одной транзакции: повтор запроса с тем же ключом
-- либо находит готовый результат, либо (если первая попытка не зафиксирована) создаёт его заново,
-- но никогда не создаёт второе сообщение.
-- Миграция только добавляет таблицу: версия API из lab2 продолжает работать с этой схемой.
CREATE TABLE idempotency_keys (
user_id uuid NOT NULL REFERENCES users (id),
method text NOT NULL,
path text NOT NULL,
key text NOT NULL,
request_hash text NOT NULL, -- sha256 разобранного тела: другое тело с тем же ключом — 409
message_id uuid NOT NULL REFERENCES messages (id),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, method, path, key),
CONSTRAINT idempotency_keys_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$')
);
-- Удаление ключей старше срока хранения (IDEMPOTENCY_TTL_SECONDS, не меньше 24 часов).
CREATE INDEX idempotency_keys_created_at_idx ON idempotency_keys (created_at);
+6
View File
@@ -0,0 +1,6 @@
# Прямые зависимости API. Точные версии всех пакетов с хешами — в requirements.txt,
# он генерируется из этого файла командой из REPORT.md («Обновление зависимостей»).
psycopg[binary]==3.3.6
psycopg-pool==3.3.3
valkey==6.1.1
argon2-cffi==25.1.0
+243
View File
@@ -0,0 +1,243 @@
#
# This file is autogenerated by pip-compile with Python 3.14
# by the following command:
#
# pip-compile --allow-unsafe --generate-hashes --no-emit-index-url --output-file=requirements.txt --strip-extras requirements.in
#
argon2-cffi==25.1.0 \
--hash=sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1 \
--hash=sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741
# via -r requirements.in
argon2-cffi-bindings==26.1.0 \
--hash=sha256:061a6919145bbf282ebf1f9c59d3135d4833c25313c8595c0d68cf7712ddfce2 \
--hash=sha256:0cc40f7b4050bb93eb67de95d2d759322fc7ce4930b9d645581ecf4913ec651e \
--hash=sha256:151dfaad9de753f4af2a7854e707e4784f2acc434340ade64239c5b104b2d605 \
--hash=sha256:19423e5d7ac1cc354baab59eaabf18db2ec04ef6593b5abe5a34f323c4a8f87a \
--hash=sha256:19b562b1de4b9052ef1214a2821c44b6e6f22945daa102c32ae4eff929d8b6d8 \
--hash=sha256:1a0a29ed86960e44eaace7e081bdfab4f08b012fd96ec8edba71e2ad020939e4 \
--hash=sha256:1af817e84578ef8b7295ad17de0f9896e4c8520dbf2233c7aa5aa3d487256fc4 \
--hash=sha256:1b0bcac4d490a237e18cf91f57352920c29f77f2fa39efd0813fb81298bf17ba \
--hash=sha256:1d98e33bd8bd67d7206c124e200bf2229c4cfa8c9c19f7b44a897f0fc71837eb \
--hash=sha256:21ca0396fe5ec995dd54431c32698189666f9224810acfa752e50d2bd94d9df2 \
--hash=sha256:224865cbbcb7a2bd1356741dff12b0134df726b6d44bb7b500df8e303cbd9e81 \
--hash=sha256:242bb0cda2ae3650764fc194593d9ea45fc9e72729acd89778c7cfe184cec2a5 \
--hash=sha256:27f1821903e2ceadcb88ec2b45ef190897b7682449c772f4d9b53e42c520cf29 \
--hash=sha256:28524438cd3e723f25412f63d4fd516ff5bae9ae5aa56acbe2a1404398a0cf31 \
--hash=sha256:2b741888c93147444fdfc851abd81cc207f37f7f7da42062a00deb3888e57da8 \
--hash=sha256:2c36ff87b5dfaa477d0bd51e9d7f6abdae7c8955d2983c97419085d842154b3e \
--hash=sha256:34b7d9c24a4165a2c61cc8ae11d44d48c9ce2830fb536cb7914e11fdd9962728 \
--hash=sha256:49d525938467d52c923a890153c99087c9d5a937d1f6b585dbdba34ec82e397a \
--hash=sha256:4f84cdd868978d7b7350a566c254042d44216d9e37f241f3a6d3b1dfebeede35 \
--hash=sha256:62ff20cd130c956c7c9144d5fe35228f98b51c579b2439e988b27ef93e16c02a \
--hash=sha256:63505c71542a44b68b1e38060450fb006404170da375feb31af153e7f9c6205d \
--hash=sha256:6376d4b3aca039375ca8bf92f770da0ec424a1ce3a37077a8d3c557411aa56ca \
--hash=sha256:6a4e68eed961a8de6928d1c17ff3dc2a547e0e923c17f8f1cd79fb7bc9502f98 \
--hash=sha256:6ab674f668d5962a3a4136ae0812519b0f1586874263723a32181d60d64137e1 \
--hash=sha256:7014ab7e6f5d8511af92544667a0346ea6dfc314ea9a7cad1dba9fdb5c9a6e33 \
--hash=sha256:76ae29acace5d33355344612844d588e19deaaba4639d8bb01601e4b1418ef36 \
--hash=sha256:78de2d65e0b9ea7ce9d1b1c3e87297b2d7305a02c266ee2a2d6910daddd7ee69 \
--hash=sha256:9bacedc04b0402837586a17f0919e3dfdd95291f441f1f56bd80ec274c2840a1 \
--hash=sha256:a86c069c91a747a2c4e5c51473590aeb48172fff9b2130d23729a42d98665ecb \
--hash=sha256:ac82fc756a446b6ccd7139ce70efa9d8bbe541e7ad579a12dcb52764b7175c5f \
--hash=sha256:af11ac37a7c53dc16cb7950a6190851b0870fe218b6c60c0bb7ac355234e3083 \
--hash=sha256:b70225b5fd1e0d2ef4f7fd30d24658454535f0924dff0caca5dc08efbbbadfbb \
--hash=sha256:c49e853a3bef9dd10329f31f702e7fa9b5c58229ff9c2ff6d069efaf09177c08 \
--hash=sha256:ccaf0a46cbb380f1fd102a874e32aa629fd3cb0c0e94f4943fa1f6d5edc5dac6 \
--hash=sha256:d157ddfab1e8b21f2f1dedda9c09645d98b5ed0b667b0626be600a345d426440 \
--hash=sha256:d88e5f7e60f28ae0b0cc6b2f16c43e87cd642a196a86f85e0d8bb6fe016fc16d \
--hash=sha256:db0fcd827ca61622a01b220aadfbece01939acf53888f2cb98cd93e9b1e2c97e \
--hash=sha256:df612391feca41c44d20118f3b88d1b86419465cd1f5496859f715ca60ec2210 \
--hash=sha256:f0c3103fcff20183e593459cfea6e012281c0e76ae3ed8b5565ad1b92eac3990 \
--hash=sha256:f9c4420a7a864fe1b86ce35befc95b8e39fb852493b81cf798671ddc265de638 \
--hash=sha256:ffff613aaa9ce6236766e2fc6dc560bb5abde7a2e2416e3db1f9ae395a2b4dd4
# via argon2-cffi
cffi==2.1.1 \
--hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \
--hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \
--hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \
--hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \
--hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \
--hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \
--hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \
--hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \
--hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \
--hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \
--hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \
--hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \
--hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \
--hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \
--hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \
--hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \
--hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \
--hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \
--hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \
--hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \
--hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \
--hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \
--hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \
--hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \
--hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \
--hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \
--hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \
--hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \
--hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \
--hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \
--hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \
--hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \
--hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \
--hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \
--hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \
--hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \
--hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \
--hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \
--hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \
--hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \
--hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \
--hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \
--hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \
--hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \
--hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \
--hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \
--hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \
--hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \
--hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \
--hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \
--hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \
--hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \
--hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \
--hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \
--hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \
--hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \
--hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \
--hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \
--hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \
--hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \
--hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \
--hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \
--hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \
--hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \
--hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \
--hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \
--hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \
--hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \
--hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \
--hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \
--hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \
--hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \
--hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \
--hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \
--hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \
--hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \
--hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \
--hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \
--hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \
--hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \
--hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \
--hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \
--hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \
--hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \
--hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \
--hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \
--hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \
--hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \
--hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \
--hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \
--hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \
--hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \
--hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \
--hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \
--hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \
--hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \
--hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \
--hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \
--hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \
--hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264
# via argon2-cffi-bindings
psycopg==3.3.6 \
--hash=sha256:a1db9f7148b06a28606767efaca51fa6f9398c5c0a3810519be69d7000bdb631 \
--hash=sha256:c081f2250df751a943036e42db6df4571c66cd0aabe8291a7a506512b12007d2
# via -r requirements.in
psycopg-binary==3.3.6 \
--hash=sha256:05a83ac9fd52b9bca7cb5ab04b3691163170bd16f53defa27216ea3aa07ee781 \
--hash=sha256:0a52991594ac4db888c7d39bccef331797e30cb31a95cae02cf2607f83a42dc2 \
--hash=sha256:0bf08b749cc144f33b44a91b78e3f71c60eb07963746a0df5a100b36ce3d7475 \
--hash=sha256:0ebfad5d131de9f892ae9e70cc7616207768b6714b66a52d4612b8ceaf78b372 \
--hash=sha256:1679a1cb93fbe5a6d1fd58d82cbddcc6fcb8c61446ba7cae6eb2a7b19bc585de \
--hash=sha256:198a48e68cc99ccac03ba95ac857e73aa66f3bf6be77019fafb0832a05f7ad03 \
--hash=sha256:1fbd30e537dab22cafdf080608f10148fe2a5f3a61294ddb5113caac8a623840 \
--hash=sha256:289aadd6a00e151203c081f708348ec89f1e483c9b510ef4ac3981f847f01f79 \
--hash=sha256:2f122603f36050937982abf9668d8bc4769a79f7c93a65013b1c49f1cab7b56b \
--hash=sha256:303732e798fe6729f8e12021b9c96107df8e95ecec4dd487c67b98ec2a59435e \
--hash=sha256:31cd942c23f613276b81a6e6598cefa12960058b0f46e1e874b540c793f6aca5 \
--hash=sha256:366db6e97e66b37211475f20c4c1324a2dc0dd825e46d4e87f9d599304d276f9 \
--hash=sha256:373704aea331d3f3e3402c125a1543f5875e2986ebb54f97d1647942161f803f \
--hash=sha256:37d40450659401600e6d043ff586c89a71a69f33cbb8bcdba6cdb2569beecdbe \
--hash=sha256:37e517c146b185f9c0c6e8d0a0ebbdeeeb67896af28466e032bc810d0c7dc7a7 \
--hash=sha256:3af90f92769d8cc10f94515ee7a0aef36ea85ca733a0ce22858f6e0953f41138 \
--hash=sha256:3c9e663b2e800e3218994cf948c11bcc2844e6491b34aa80d089baf6531827bf \
--hash=sha256:3f84dab25e0385692ee13274c68678377e0b1a70ab9d14e56264cbf61f60c62d \
--hash=sha256:4690cf67738f0e0e49a32aeec99bf0e4595cc2b4f1af984a4345394b1dcff91a \
--hash=sha256:566dd827f17728efdf7d88a5b066f815170f6fdad13967ae952842d90e6aaa9f \
--hash=sha256:5927b7ba63153cd8e9862987290a2b783a5c590daf2a4ef981700cc3569166d4 \
--hash=sha256:5ad8f35e67cc16d1fad1fa8c88972dc9b3a3141ea67897399904edab96a301b6 \
--hash=sha256:5ea8beeb5541780b4b50b462eeacbc4f594ce3b911dc20c81c75f267876f71d2 \
--hash=sha256:5f598f19fa9a91540b5cee17932ffd227b7b53a481605bcc4573c0eafa647300 \
--hash=sha256:612382ac3ed13651c7fa44b5fee9fbf7baaa2ddbc6f500391672682c5f1df9e0 \
--hash=sha256:6ff05561e4a067d35507dc5c90f1deb2ec1c9703ac5cccc1bc26e08a197f9c5a \
--hash=sha256:7308c93cf0b19bbaf8e6ff0a6ad50d3c442385739245fe15a8d593bf841734a6 \
--hash=sha256:79a2a1c3449f6c3409427078ed1cec10de79f3023cb5f2504f0597d350ad46c7 \
--hash=sha256:7beb3e41c9a1e509f3ed85263386588cbe3e975aa67be21f79f44fd35ffaeefc \
--hash=sha256:86147cb5d140341c3363fb5bacce31f8d5543902a46699d3c536b101bbceaf9e \
--hash=sha256:889e42acec10450185e0cdfb396f375e2c1a8d7737c114830a7fde4654f59e30 \
--hash=sha256:910ace140e3e7b7596898d083f37a8fe90c5c40684252ad4e682364b2cd3deba \
--hash=sha256:955e3dd94da361e052d2e49acf591017158dc8f8ed2c8a42c2e3943403c39dc2 \
--hash=sha256:9892188bb15e5803beb51afe8a25add6b56be391a53058e8bca03b74e1e6bf22 \
--hash=sha256:98c02090d88f2ebc0ec1e8da538f77d225ce0fffecf372aa39262e62a1b054ef \
--hash=sha256:9b2f11794e017ce340934e35de46181c46ef71ec75ea3d85dd75cd836761c01e \
--hash=sha256:a2e44a342d2aee40508e28a563d8961c39d9bbd8cae36d8578f0a3c6658aab0f \
--hash=sha256:a4ee3bdd5468a725f2a4d9aab8a74b6d0279f768c8b5d3aeb102c5307ff3d59c \
--hash=sha256:a5165300324efd5a772c48a88ab3a928513ab3979fca76553e62ee815f7b2b9c \
--hash=sha256:a9348c5b43a3bb5ef8c2e89d5237c9c87eeafb01d338c84a7aebbc5cd0313299 \
--hash=sha256:aa73160077345ec21b3f51e8e24b3de2e99586217e497629326eb9b2ea88c52e \
--hash=sha256:ad1c785e784cfd87e8436c6b7702f2d321fc39601bbaf29bc63a41a867091638 \
--hash=sha256:b3f75dee0f9afafabe4edc52c4842f1e1878ed2069bd05b22d6fe961e97e4dba \
--hash=sha256:b599defe9190b17e9907c8b4d114c181e702c87efcd1b8a0ad40971cdcc4634a \
--hash=sha256:b82491019b884d62318b5f30706c3d7e6d4e5a6cb7eabcb3edc0c1b0fdaceae9 \
--hash=sha256:b8ece331509f7a975b90501f41e83ad905e4141753fedf3f2711b2bc70a8efbc \
--hash=sha256:b979a42815410432420275412633960807178b1ce26591a16ce06e78a5bd4bb2 \
--hash=sha256:be4f9b3c9338ac5dd217c5847e21521b396c8117f78dc420d495a5c49bbef874 \
--hash=sha256:bf8c8481d026b85dd70c5fa7dde85b2333aed0b32a2602bcd38a900cbd78a49c \
--hash=sha256:c61617eaae0112ca154da87ffb99b73af2c74067acac28dfb9a4455b019dff2e \
--hash=sha256:c6d19cb4999d03231e8730a5f66c8f5068bc3b532677eb39dab0f600bff3e312 \
--hash=sha256:c7753871eb57e6a5f4646f6168590c6653073dea5e9e720b201c8875332df4c8 \
--hash=sha256:c7f92daa0d2a1c76f07264abddf8cbabd30152a2f09c3270e50f0c7efdf5dcac \
--hash=sha256:cbd5f73073ed19c378d4c35499db1e3e703a5b1a324e521204065967bfaa7a18 \
--hash=sha256:cec5ea900390897d0b46130f60bc2883bf19c314f9044235217c8be88b0ef269 \
--hash=sha256:d636338c8f21b0df2f84657b00bc34f9313f826ef93f1155bc743607e4a0c5eb \
--hash=sha256:dc75da5a20951049f7b773145f998f69d181adad9c58a0ff36e0cf1d73c10e10 \
--hash=sha256:e23a66a763fbe83fcc210bc77c27e5a5ea380ebf091c06f34d8561b695e5a40f \
--hash=sha256:e8cbb54454dbf1bbf2ff08dd7693e8d94ac94b1a20f70f4b3b813d52ecb5cbc1 \
--hash=sha256:ee2c4728c691245e24501fcd7a97b5b381236b9985bc445bba88cdce7d1b5784 \
--hash=sha256:f0535693ce476a722b718b002d5d2c27d47e71ca945276ac194409c98e74c492 \
--hash=sha256:f19cc87343eaa55255e76b31259a570072ac95d6ae82c92dd34b97691f5e49dc \
--hash=sha256:f21d057f3e5f5491067e5b292498073b73847d48799b099803fef100775fcc52 \
--hash=sha256:f87dbdc42e78ee0f7ea180c03f8c78e80a949e373066629bd90fefff10552dff \
--hash=sha256:fa34eb47969297471db7b7f193622c7e3ee839ec05abd05f1fe104d5b1b1dcf4 \
--hash=sha256:fdccb3a0e184b03e9baa673b15a809cf36c339c85dbda0ebc25a698846dfbee8
# via psycopg
psycopg-pool==3.3.3 \
--hash=sha256:9b9cd6a4fcec47a410f7e82d408540e7f77b478509e91b44c1a5457a13e5ff37 \
--hash=sha256:df87b5d9d0ad7db37f6cdad4fa8ce113d250f5997f6db38e9a99192fb67f9e1d
# via -r requirements.in
pycparser==3.0 \
--hash=sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29 \
--hash=sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992
# via cffi
typing-extensions==4.16.0 \
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
--hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
# via psycopg-pool
valkey==6.1.1 \
--hash=sha256:5880792990c6c2b5eb604a5ed5f98f300880b6dd92d123819b66ed54bb259731 \
--hash=sha256:e2691541c6e1503b53c714ad9a35551ac9b7c0bbac93865f063dbc859a46de92
# via -r requirements.in
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""EXPLAIN (ANALYZE, BUFFERS) of the history page query on 10 000+ messages.
python scripts/explain_history.py --output evidence/explain.txt
The stand must be running. The script registers two synthetic users through the API,
creates a target chat and a noise chat, bulk-inserts messages with SQL, runs ANALYZE and
prints the plans of the same query the API runs (src/messenger/db.py, list_messages):
first page, a page in the middle, the last page, the generic plan of the parameterized
query, and for comparison the middle page without the index (DROP INDEX inside a
transaction that is rolled back, so the database is left unchanged).
Standard library only.
"""
import argparse
import base64
import json
from pathlib import Path
import subprocess
import sys
import time
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[1]
BASE = 'http://127.0.0.1:8080'
PSQL = ['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
'-X', '-v', 'ON_ERROR_STOP=1']
PAGE = 51 # limit 50 + 1 row to learn whether the next page exists, as the API does
lines = []
def out(text=''):
lines.append(text)
print(text, flush=True)
def psql(sql, echo=True):
"""Run SQL in one psql session; with echo the transcript shows every statement before its result."""
args = PSQL + (['--echo-all'] if echo else ['-At']) + ['-f', '-']
done = subprocess.run(args, cwd=str(ROOT), input=sql.encode('utf-8'), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
text = done.stdout.decode('utf-8', 'replace').strip()
if done.returncode != 0:
out(text)
raise SystemExit('psql failed')
return text
def api(method, path, body=None, headers=None):
headers = dict(headers or {})
data = None
if body is not None:
data = json.dumps(body).encode('utf-8')
headers['Content-Type'] = 'application/json'
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
with urllib.request.urlopen(request, timeout=10) as response:
return json.loads(response.read())
def user(label):
username = label + '_' + uuid.uuid4().hex[:10]
password = 'Explain-' + uuid.uuid4().hex
created = api('POST', '/api/v1/users', {'username': username, 'display_name': label, 'password': password})
credential = base64.b64encode((username + ':' + password).encode()).decode()
session = api('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential})
return created['id'], session['token']
def page_sql(chat_id, after=None):
"""The same SQL text as Repository.list_messages, with literal values."""
sql = "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '%s' " % chat_id
if after:
sql += "AND (created_at, id) > ('%s', '%s') " % after
return sql + 'ORDER BY created_at, id LIMIT %d' % PAGE
def main():
parser = argparse.ArgumentParser(description='EXPLAIN of the history query; inserts synthetic messages')
parser.add_argument('--messages', type=int, default=10000, help='messages in the target chat (>= 10000)')
parser.add_argument('--noise', type=int, default=20000, help='messages in another chat')
parser.add_argument('--output', default=None)
args = parser.parse_args()
sys.stdout.reconfigure(errors='replace')
out('# %s UTC, %s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()), psql('SELECT version()', echo=False)))
alice, alice_token = user('explain_a')
bob, _ = user('explain_b')
target = api('POST', '/api/v1/chats', {'title': 'EXPLAIN target', 'member_ids': [alice, bob]},
{'Authorization': 'Bearer ' + alice_token})['id']
noise = api('POST', '/api/v1/chats', {'title': 'EXPLAIN noise', 'member_ids': [alice]},
{'Authorization': 'Bearer ' + alice_token})['id']
out('# target chat %s: %d messages; noise chat %s: %d messages' % (target, args.messages, noise, args.noise))
started = time.monotonic()
psql('''
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '%(target)s', CASE WHEN i %% 2 = 0 THEN '%(alice)s'::uuid ELSE '%(bob)s'::uuid END,
'seed message ' || i, clock_timestamp() + i * interval '1 millisecond'
FROM generate_series(1, %(messages)d) AS i;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '%(noise)s', '%(alice)s', 'noise message ' || i, clock_timestamp() + i * interval '1 millisecond'
FROM generate_series(1, %(noise_count)d) AS i;
ANALYZE messages;
''' % {'target': target, 'noise': noise, 'alice': alice, 'bob': bob, 'messages': args.messages, 'noise_count': args.noise},
echo=False)
out('# inserted and analyzed in %.1f s' % (time.monotonic() - started))
out(psql("SELECT 'messages total: ' || count(*) || ', in target chat: ' || count(*) FILTER (WHERE chat_id = '%s') FROM messages" % target, echo=False))
def key_at(position):
row = psql("SELECT created_at || '|' || id FROM messages WHERE chat_id = '%s' ORDER BY created_at, id OFFSET %d LIMIT 1"
% (target, position - 1), echo=False)
return tuple(row.split('|'))
middle, last = key_at(args.messages // 2), key_at(args.messages - 20)
explain = 'EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) '
out()
out('== 1. First page, middle page and last page: index range scan, no sort ==')
out(psql('\n'.join(explain + page_sql(target, after) + ';' for after in (None, middle, last))))
out()
out('== 2. Generic plan of the parameterized query (how a prepared statement with $1..$4 runs) ==')
out(psql('''SET plan_cache_mode = force_generic_plan;
PREPARE history_page(uuid, timestamptz, uuid, int) AS
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4;
%sEXECUTE history_page('%s', '%s', '%s', %d);''' % (explain, target, middle[0], middle[1], PAGE)))
out()
out('== 3. For comparison: the same middle page without the index (rolled back) ==')
out(psql('''BEGIN;
DROP INDEX messages_chat_history_idx;
%s%s;
ROLLBACK;''' % (explain, page_sql(target, middle))))
out(psql("SELECT 'index still exists: ' || (to_regclass('messages_chat_history_idx') IS NOT NULL)", echo=False))
if args.output:
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
Path(args.output).write_text('\n'.join(lines) + '\n', encoding='utf-8')
if __name__ == '__main__':
main()
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Create local secret files for the compose stand.
python scripts/init_secrets.py
Passwords are random and synthetic; they are created only if missing and never printed.
The URL/config files are always rebuilt from the password files, so the pair stays consistent.
secrets/ is listed in .gitignore and .dockerignore.
PostgreSQL applies its password only when the data volume is created. If secrets/ is
deleted while the pgdata volume is kept, restore the old files or recreate the volume
(docker compose down -v deletes ALL lab data).
"""
from pathlib import Path
import secrets
ROOT = Path(__file__).resolve().parents[1]
DIR = ROOT / 'secrets'
def write(name, content):
path = DIR / name
path.write_text(content, encoding='utf-8', newline='\n')
# Readable for the non-root users inside containers (files are bind-mounted as is).
path.chmod(0o644)
def password(name):
path = DIR / name
if path.is_file() and path.read_text(encoding='utf-8').strip():
print('keep secrets/' + name)
return path.read_text(encoding='utf-8').strip()
value = secrets.token_hex(24) # hex: safe inside URLs without escaping
write(name, value + '\n')
print('created secrets/' + name)
return value
def main():
DIR.mkdir(exist_ok=True)
postgres = password('postgres_password')
valkey = password('valkey_password')
write('database_url', 'postgresql://messenger:%s@postgres:5432/messenger\n' % postgres)
write('valkey_auth', 'requirepass %s\n' % valkey)
write('cache_url', 'valkey://:%s@valkey:6379/0\n' % valkey)
print('written secrets/database_url, secrets/valkey_auth, secrets/cache_url')
if __name__ == '__main__':
main()
+800
View File
@@ -0,0 +1,800 @@
#!/usr/bin/env python3
"""Infrastructure checks for lab 3 that need control over the compose stand.
python -X utf8 scripts/lab3_checks.py --output evidence/lab3-checks.txt
python -X utf8 scripts/lab3_checks.py --only failover experiment rolling
The stand must already be running (docker compose up -d --build --wait). Every command is
printed together with its output. Sections stop, kill and start containers, but never delete
volumes, never flush Valkey and never print secrets or session tokens. All API traffic goes
through the load balancer on 127.0.0.1:8080, as a client would send it.
Standard library only; works on Windows, Linux and macOS (-X utf8 is needed on Windows only
because the public tests read the contract in the default encoding).
"""
import argparse
import base64
import concurrent.futures
import csv
import hashlib
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[1]
BASE = 'http://127.0.0.1:8080'
STATS = 'http://127.0.0.1:8404/;csv'
PROJECT = os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-lab3')
VALKEY_CLI = 'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_auth)" '
PSQL = ['exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-At', '-c']
PY = [sys.executable, '-X', 'utf8']
lines = []
results = []
class Stop(Exception):
pass
def out(text=''):
lines.append(text)
print(text, flush=True)
def run(command, check=True, quiet=False, env=None):
"""Run a command and echo it with its output; return (output, exit code, seconds)."""
out('$ ' + ' '.join(command))
started = time.monotonic()
done = subprocess.run(command, cwd=str(ROOT), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
elapsed = time.monotonic() - started
text = done.stdout.decode('utf-8', 'replace').strip()
if text and not quiet:
out(text)
if check and done.returncode != 0:
if quiet and text:
out(text)
raise Stop('command failed with exit code %d' % done.returncode)
return text, done.returncode, elapsed
def silent(command):
"""Run a command without echo; return its stdout."""
return subprocess.run(command, cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True).stdout.strip()
def compose(*args, **kwargs):
return run(['docker', 'compose'] + list(args), **kwargs)
def psql(sql, quiet=False):
if quiet:
return silent(['docker', 'compose'] + PSQL + [sql])
return compose(*(PSQL + [sql]))[0]
def valkey_cli(command):
return compose('exec', '-T', 'valkey', 'sh', '-c', VALKEY_CLI + command)[0]
def verdict(name, ok, detail=''):
results.append((name, ok))
out('=> %s: %s%s' % ('PASS' if ok else 'FAIL', name, ' (' + detail + ')' if detail else ''))
out()
def http(method, path, token=None, body=None, headers=None, timeout=10):
"""(status, parsed JSON or None, seconds, X-Instance-Id); status None when the connection fails."""
all_headers = dict(headers or {})
if token:
all_headers['Authorization'] = 'Bearer ' + token
data = None
if body is not None:
data = json.dumps(body).encode('utf-8')
all_headers['Content-Type'] = 'application/json'
request = urllib.request.Request(BASE + path, data=data, headers=all_headers, method=method)
started = time.monotonic()
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
raw, status, instance = response.read(), response.status, response.headers.get('X-Instance-Id')
except urllib.error.HTTPError as error:
with error:
raw, status, instance = error.read(), error.code, error.headers.get('X-Instance-Id')
except OSError:
return None, None, time.monotonic() - started, None
try:
payload = json.loads(raw) if raw else None
except ValueError:
payload = None
return status, payload, time.monotonic() - started, instance
def basic(username, password):
return {'Authorization': 'Basic ' + base64.b64encode((username + ':' + password).encode()).decode()}
def new_user(label='check'):
"""Register a synthetic user and log in: (user, password, token). The token is never printed."""
username = label + '_' + uuid.uuid4().hex[:12]
password = 'Check-' + uuid.uuid4().hex
status, user, _, _ = http('POST', '/api/v1/users', body={'username': username, 'display_name': 'Check', 'password': password})
if status != 201:
raise Stop('registration failed with %s' % status)
status, session, _, _ = http('POST', '/api/v1/auth/sessions', headers=basic(username, password))
if status != 201:
raise Stop('login failed with %s' % status)
return user, password, session['token']
def post_message(token, chat_id, text, key):
return http('POST', '/api/v1/chats/%s/messages' % chat_id, token, {'text': text}, {'Idempotency-Key': key}, timeout=5)
def history(token, chat_id):
items, cursor = [], None
while True:
path = '/api/v1/chats/%s/messages?limit=100' % chat_id + ('&cursor=' + cursor if cursor else '')
status, page, _, _ = http('GET', path, token)
if status != 200:
raise Stop('history read failed with %s' % status)
items += page['items']
cursor = page['next_cursor']
if not cursor:
return items
def wait_ready(seconds=60):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if http('GET', '/health/ready', timeout=3)[0] == 200:
return True
time.sleep(0.5)
return False
def api_replicas(all_states=False):
"""{short container id: container name} of the api service of this project."""
command = ['docker', 'ps', '--filter', 'label=com.docker.compose.project=' + PROJECT,
'--filter', 'label=com.docker.compose.service=api', '--format', '{{.ID}} {{.Names}}']
if all_states:
command.insert(2, '-a')
return dict(line.split(' ', 1) for line in silent(command).splitlines() if line)
def container(service):
return silent(['docker', 'compose', 'ps', '-a', '-q', service])
def inspect(target, template):
return silent(['docker', 'inspect', '-f', template, target])
def wait_replicas(count, seconds=90):
"""Wait until `count` api replicas are healthy and all of them answer through the load balancer."""
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
replicas = api_replicas()
healthy = [r for r in replicas if inspect(r, '{{.State.Health.Status}}') == 'healthy']
if len(healthy) == count:
seen = {http('GET', '/health/live', timeout=3)[3] for _ in range(4 * count)}
if set(healthy) <= seen:
return True
time.sleep(1)
return False
def show(label, result):
status, payload, seconds, instance = result
code = payload['error']['code'] if isinstance(payload, dict) and 'error' in payload else ''
out('%-58s -> %s %s in %.2f s, X-Instance-Id %s' % (label, status, code, seconds, instance or '-'))
return status
class StatsPoller(threading.Thread):
"""Polls the HAProxy stats CSV every 100 ms and records when each server slot changes state.
A slot (api1..api8) is matched to a container once, by its IP address while it is UP.
A stopped replica first turns DOWN (failed checks); a killed one usually goes to
MAINT (resolution) first, because Docker DNS drops its address and the slot loses it.
"""
def __init__(self):
super().__init__(daemon=True)
self.stop_event = threading.Event()
self.changes = [] # (monotonic time, slot, new status)
@staticmethod
def snapshot():
"""{slot: (status, ip)} for the api backend."""
try:
with urllib.request.urlopen(STATS, timeout=1) as response:
text = response.read().decode('utf-8').lstrip('# ')
except OSError:
return {}
return {row['svname']: (row['status'].split(' ')[0], row.get('addr', '').split(':')[0])
for row in csv.DictReader(io.StringIO(text))
if row.get('pxname') == 'api' and row.get('svname') not in ('FRONTEND', 'BACKEND')}
def slot_of(self, address):
for slot, (status, ip) in self.snapshot().items():
if ip == address:
return slot
return None
def run(self):
last = {}
while not self.stop_event.is_set():
now = time.monotonic()
for slot, (status, _) in self.snapshot().items():
if last.get(slot) != status:
self.changes.append((now, slot, status))
last[slot] = status
time.sleep(0.1)
def first_change(self, slot, statuses, after):
for moment, changed, status in self.changes:
if changed == slot and status in statuses and moment >= after:
return moment
return None
class Load:
"""Closed-loop load through the load balancer: each worker posts a message and reads /users/me.
A failed POST is retried with the SAME Idempotency-Key and body, exactly like a careful client,
so the final history must contain every acknowledged message once and no duplicates.
"""
def __init__(self, workers=6):
self.user, _, self.token = new_user(label='load')
self.chat = http('POST', '/api/v1/chats', self.token, {'title': 'Load', 'member_ids': [self.user['id']]})[1]
self.workers = workers
self.events = [] # (monotonic time, ok, instance, kind)
self.acknowledged = []
self.lock = threading.Lock()
self.stop_event = threading.Event()
self.threads = []
def worker(self, index):
while not self.stop_event.is_set():
key = uuid.uuid4().hex
text = 'load %d %s' % (index, key)
while not self.stop_event.is_set():
status, payload, _, instance = post_message(self.token, self.chat['id'], text, key)
with self.lock:
self.events.append((time.monotonic(), status == 201, instance, 'write'))
if status == 201:
self.acknowledged.append(payload['id'])
if status == 201:
break
time.sleep(0.05)
status, _, _, instance = http('GET', '/api/v1/users/me', self.token, timeout=5)
with self.lock:
self.events.append((time.monotonic(), status == 200, instance, 'read'))
def start(self):
for index in range(self.workers):
thread = threading.Thread(target=self.worker, args=(index,), daemon=True)
thread.start()
self.threads.append(thread)
def stop(self):
self.stop_event.set()
for thread in self.threads:
thread.join(timeout=10)
def window(self, start, end):
with self.lock:
selected = [e for e in self.events if start <= e[0] < end]
ok = sum(1 for e in selected if e[1])
return {'requests': len(selected), 'ok': ok, 'errors': len(selected) - ok,
'ok_rps': round(ok / (end - start), 1) if end > start else 0.0}
def max_gap(self, start, end):
"""Longest interval without a successful request."""
with self.lock:
moments = sorted(e[0] for e in self.events if e[1] and start <= e[0] < end)
points = [start] + moments + [end]
return max(b - a for a, b in zip(points, points[1:]))
def last_served_by(self, instance, after):
with self.lock:
moments = [e[0] for e in self.events if e[2] == instance and e[0] >= after]
return max(moments) if moments else None
def first_served_by(self, instance, after):
with self.lock:
moments = [e[0] for e in self.events if e[2] == instance and e[0] >= after]
return min(moments) if moments else None
def verify(self):
"""(acknowledged, in history, duplicates by text) for the load chat."""
items = history(self.token, self.chat['id'])
texts = [m['text'] for m in items]
ids = {m['id'] for m in items}
return len(set(self.acknowledged)), len(set(self.acknowledged) & ids), len(texts) - len(set(texts))
# --- sections ---------------------------------------------------------------
def section_stack():
out('== Stack: replicas, pinned images, health, limits, published ports, secrets ==')
compose('ps', '-a', '--format', 'table {{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}')
config = json.loads(compose('config', '--format', 'json', quiet=True)[0])
services = config['services']
images = {name: services[name].get('image', '') for name in ('lb', 'postgres', 'valkey')}
verdict('third-party images are pinned by tag and digest', all('@sha256:' in image for image in images.values()),
', '.join(images.values()))
replicas = api_replicas()
names = sorted(replicas.values())
out('api replicas: ' + ', '.join('%s (%s)' % (name, cid) for cid, name in sorted(replicas.items(), key=lambda x: x[1])))
no_container_name = not any('container_name' in service for service in services.values())
verdict('at least two api replicas of one compose service, no container_name', len(replicas) >= 2 and no_container_name,
', '.join(names))
health = {name: inspect(cid, '{{.State.Health.Status}}') for cid, name in replicas.items()}
for service in ('postgres', 'valkey'):
health[service] = inspect(container(service), '{{.State.Health.Status}}')
out('health: ' + ', '.join('%s=%s' % item for item in sorted(health.items())))
verdict('all api replicas, postgres and valkey are healthy', set(health.values()) == {'healthy'})
users = {name: silent(['docker', 'exec', cid, 'id', '-u']) for cid, name in replicas.items()}
verdict('API processes do not run as root', set(users.values()) == {'10001'}, ', '.join('%s uid=%s' % i for i in sorted(users.items())))
out('%-26s %8s %10s %s' % ('container', 'cpus', 'memory', 'published ports'))
limited, bypass = True, []
targets = [(name, cid) for cid, name in replicas.items()] + [(s, container(s)) for s in ('lb', 'postgres', 'valkey')]
for name, cid in sorted(targets):
cpus = int(inspect(cid, '{{.HostConfig.NanoCpus}}') or 0) / 1e9
memory = int(inspect(cid, '{{.HostConfig.Memory}}') or 0) // (1024 * 1024)
ports = inspect(cid, '{{range $p, $b := .HostConfig.PortBindings}}{{range $b}}{{.HostIp}}:{{.HostPort}}->{{$p}} {{end}}{{end}}')
out('%-26s %8.2f %8d MB %s' % (name, cpus, memory, ports or '-'))
limited = limited and cpus > 0 and memory > 0
if ports and name != 'lb':
bypass.append(name)
if ports and any(not part.startswith('127.0.0.1:') for part in ports.split()):
bypass.append(name + ' (not 127.0.0.1)')
verdict('every container has CPU and memory limits', limited)
verdict('only the load balancer publishes ports, and only on 127.0.0.1', not bypass, ', '.join(bypass))
secrets = {name: sorted(s['source'] for s in service.get('secrets', [])) for name, service in services.items()}
out('secrets per service: ' + '; '.join('%s=%s' % (k, ','.join(v) or '-') for k, v in sorted(secrets.items())))
verdict('secrets are given only where needed', secrets.get('lb') == [] and secrets['api'] == ['cache_url', 'database_url']
and secrets['postgres'] == ['postgres_password'] and secrets['valkey'] == ['valkey_auth'])
aof = ' '.join(valkey_cli('CONFIG GET ' + name) for name in ('appendonly', 'appendfsync', 'maxmemory-policy'))
verdict('Valkey persistence is AOF with fsync always, no eviction', all(w in aof.split() for w in ('yes', 'always', 'noeviction')))
def section_migrations():
out('== Migrations: run once by the migrate service, idempotent re-run ==')
psql("SELECT version || ' ' || applied_at FROM schema_migrations ORDER BY version")
psql("SELECT format('%s %s %s', conrelid::regclass, contype, conname) FROM pg_constraint "
"WHERE conrelid::regclass::text = 'idempotency_keys' ORDER BY 1")
before = psql("SELECT (SELECT count(*) FROM schema_migrations) || ' ' || (SELECT count(*) FROM users)")
output = compose('run', '--rm', '--no-deps', 'migrate')[0]
after = psql("SELECT (SELECT count(*) FROM schema_migrations) || ' ' || (SELECT count(*) FROM users)")
out('schema_migrations and users rows before/after: %s / %s' % (before, after))
verdict('re-running migrations applies nothing and duplicates nothing', 'applied_now=0' in output and before == after)
def section_balancing():
out('== Balancing: one session, many replicas ==')
_, _, token = new_user(label='balance')
replicas = api_replicas()
counts = {}
for _ in range(40):
status, _, _, instance = http('GET', '/api/v1/users/me', token)
counts[(instance, status)] = counts.get((instance, status), 0) + 1
for (instance, status), count in sorted(counts.items(), key=str):
out('X-Instance-Id %s (%s): %d responses with status %s' % (instance, replicas.get(instance, 'unknown container'), count, status))
instances = {instance for instance, _ in counts}
verdict('40 requests with one token are served by every replica without a new login',
instances == set(replicas) and {status for _, status in counts} == {200})
def section_idempotency():
out('== Idempotency: 20 parallel POSTs with one key through the load balancer ==')
user, _, token = new_user(label='idem')
chat = http('POST', '/api/v1/chats', token, {'title': 'Idempotency', 'member_ids': [user['id']]})[1]
key, text = uuid.uuid4().hex, 'idempotent ' + uuid.uuid4().hex
barrier = threading.Barrier(20)
def post(_):
barrier.wait()
return post_message(token, chat['id'], text, key)
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as pool:
responses = list(pool.map(post, range(20)))
statuses = sorted({r[0] for r in responses}, key=str)
ids = {r[1]['id'] for r in responses if r[0] == 201}
instances = {r[3] for r in responses}
rows = psql("SELECT count(*) FROM messages WHERE chat_id = '%s'" % chat['id'])
keys = psql("SELECT count(*) FROM idempotency_keys WHERE key = '%s'" % key)
out('statuses: %s; distinct message ids: %d; replicas that answered: %s' % (statuses, len(ids), ', '.join(sorted(instances))))
out('messages in the chat: %s; idempotency_keys rows for the key: %s' % (rows, keys))
conflict = show('same key, another body', post_message(token, chat['id'], text + ' changed', key))
verdict('one message for 20 concurrent requests with one key on several replicas',
statuses == [201] and len(ids) == 1 and len(instances) >= 2 and rows == '1' and keys == '1')
verdict('the same key with another body is rejected with 409', conflict == 409)
def section_rollback():
out('== Rollback: chat creation fails on the second INSERT ==')
user, _, token = new_user(label='rollback')
title = 'rollback-probe-' + uuid.uuid4().hex[:10]
status = show('POST /api/v1/chats with one unknown member',
http('POST', '/api/v1/chats', token, {'title': title, 'member_ids': [user['id'], str(uuid.uuid4())]}))
rows = psql("SELECT count(*) FROM chats WHERE title = '%s'" % title)
orphans = psql('SELECT count(*) FROM chats c WHERE NOT EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)')
out('rows in chats with this title: %s; chats without members: %s' % (rows, orphans))
verdict('composite chat creation is rolled back as a whole', status == 400 and rows == '0' and orphans == '0')
def section_race():
out('== Registration race: 20 parallel requests with one username ==')
username = 'race_' + uuid.uuid4().hex[:12]
barrier = threading.Barrier(20)
def register(index):
barrier.wait()
body = {'username': username, 'display_name': 'Race %d' % index, 'password': 'Race-password-%02d' % index}
return http('POST', '/api/v1/users', body=body)
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as pool:
responses = list(pool.map(register, range(20)))
statuses = sorted((r[0] for r in responses), key=str)
out('statuses: ' + ' '.join(str(s) for s in statuses) + '; replicas: ' + ', '.join(sorted({r[3] for r in responses})))
rows = psql("SELECT count(*) FROM users WHERE username = '%s'" % username)
out('rows in users with this username: ' + rows)
verdict('exactly one registration wins, the other 19 get 409', statuses == [201] + [409] * 19 and rows == '1')
def section_pool():
replicas = len(api_replicas())
out('== Connection pools: 60 parallel clients, at most 10 connections per replica (%d replicas) ==' % replicas)
users = [new_user(label='pool') for _ in range(4)]
chats = [http('POST', '/api/v1/chats', token, {'title': 'Pool', 'member_ids': [user['id']]})[1] for user, _, token in users]
count_sql = "SELECT count(*) FROM pg_stat_activity WHERE application_name = 'messenger-api'"
stop = threading.Event()
samples = []
def sample():
while not stop.is_set():
value = psql(count_sql, quiet=True)
if value.isdigit():
samples.append(int(value))
time.sleep(0.2)
def client(index):
_, _, token = users[index % 4]
path = '/api/v1/chats/%s/messages?limit=20' % chats[index % 4]['id']
statuses = []
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
statuses.append(http('GET', path, token)[0])
return statuses
sampler = threading.Thread(target=sample)
sampler.start()
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=60) as pool:
statuses = [s for batch in pool.map(client, range(60)) for s in batch]
finally:
stop.set()
sampler.join()
counts = {status: statuses.count(status) for status in sorted(set(statuses), key=str)}
out('requests: %d, statuses: %s' % (len(statuses), counts))
out('API connections in pg_stat_activity, %d samples: max %s' % (len(samples), max(samples) if samples else '-'))
verdict('pools never open more than 10 connections per replica and all requests succeed',
bool(samples) and max(samples) <= 10 * replicas and set(counts) == {200})
def section_timeouts():
out('== Timeouts: chat row locked for 6 s by another session, API answers 503 after lock_timeout=3s ==')
user, _, token = new_user(label='lock')
chat = http('POST', '/api/v1/chats', token, {'title': 'Lock', 'member_ids': [user['id']]})[1]
lock = "BEGIN; SELECT 1 FROM chats WHERE id = '%s' FOR UPDATE; SELECT pg_sleep(6); ROLLBACK;" % chat['id']
out('$ docker compose ' + ' '.join(PSQL) + ' "' + lock + '" (in the background)')
locker = subprocess.Popen(['docker', 'compose'] + PSQL + [lock], cwd=str(ROOT), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(1.5)
result = post_message(token, chat['id'], 'while locked', uuid.uuid4().hex)
show('POST message while the chat row is locked', result)
locker.wait(timeout=30)
after = show('POST message after the lock is released', post_message(token, chat['id'], 'after lock', uuid.uuid4().hex))
verdict('waiting for a lock is bounded: 503 after about 3 s, then writes work again',
result[0] == 503 and 2.5 <= result[2] <= 4.5 and after == 201, '%.2f s' % result[2])
def section_logs():
out('== Logs: useful fields, no message texts, passwords or tokens (all api replicas and lb) ==')
user, password, token = new_user(label='logs')
chat = http('POST', '/api/v1/chats', token, {'title': 'Logs', 'member_ids': [user['id']]})[1]
marker = 'log-marker-' + uuid.uuid4().hex
post_message(token, chat['id'], marker, uuid.uuid4().hex)
logs = compose('logs', '--no-log-prefix', 'api', 'lb', quiet=True)[0]
compose('logs', '--tail', '2', 'api')
compose('logs', '--no-log-prefix', '--tail', '2', 'lb')
leaked = [name for name, value in (('message text', marker), ('password', password), ('token', token)) if value in logs]
leaked += [p.name for p in (ROOT / 'secrets').glob('*_password') if p.read_text().strip() in logs]
out('searched %d log lines; found: %s' % (logs.count('\n') + 1, ', '.join(leaked) or 'nothing'))
verdict('logs contain request_id/status/duration and no secrets', 'request_id=' in logs and not leaked)
def section_expiry():
out('== Session expiry: api replicas recreated with SESSION_TTL_SECONDS=2, then restored ==')
count = len(api_replicas())
short = dict(os.environ, SESSION_TTL_SECONDS='2')
compose('up', '-d', '--no-deps', '--wait', 'api', env=short, quiet=True)
try:
if not wait_replicas(count):
raise Stop('replicas are not ready with the short TTL')
_, _, token = new_user(label='expiry')
key = 'session:' + hashlib.sha256(token.encode()).hexdigest()
first = show('GET /users/me right after login', http('GET', '/api/v1/users/me', token))
pttl = valkey_cli('PTTL ' + key)
out('PTTL of the session key in Valkey (ms): ' + pttl)
time.sleep(3)
expired = show('GET /users/me 3 s later', http('GET', '/api/v1/users/me', token))
gone = valkey_cli('EXISTS ' + key)
out('session key still exists in Valkey: ' + gone)
verdict('session expires after SESSION_TTL_SECONDS and the key disappears from Valkey',
first == 200 and 0 < int(pttl) <= 2000 and expired == 401 and gone == '0')
finally:
compose('up', '-d', '--no-deps', '--wait', 'api', quiet=True)
wait_replicas(count)
def outage(service, limit):
"""Stop one shared store and look at the answers through the load balancer."""
user, password, token = new_user(label=service)
compose('stop', service)
try:
me = show('GET /users/me with a valid token (first seconds)', http('GET', '/api/v1/users/me', token))
time.sleep(3) # the load balancer has seen failing readiness checks by now
me_later = show('GET /users/me with a valid token (after 3 s)', http('GET', '/api/v1/users/me', token))
anonymous = show('GET /users/me without a token', http('GET', '/api/v1/users/me'))
ready = show('GET /health/ready', http('GET', '/health/ready'))
slowest = max(http('GET', '/api/v1/users/me', token)[2] for _ in range(3))
out('slowest of 3 more authenticated requests: %.2f s' % slowest)
finally:
compose('start', service)
started = time.monotonic()
recovered = False
while time.monotonic() - started < 60 and not recovered:
recovered = http('GET', '/api/v1/users/me', token, timeout=5)[0] == 200
time.sleep(0.5)
out('same token after %s is back: %s' % (service, '200 after %.1f s' % (time.monotonic() - started) if recovered else 'not accepted'))
verdict('without %s: bounded 503, nothing is served as anonymous' % service,
me == 503 and me_later == 503 and anonymous in (401, 503) and ready == 503 and slowest < limit)
verdict('the stand recovers by itself when %s is back, the session is still valid' % service, recovered)
def section_valkey_down():
out('== Valkey is down ==')
outage('valkey', 3)
def section_postgres_down():
out('== PostgreSQL is down ==')
outage('postgres', 5)
def section_failover():
out('== Public failover test: tests/resilience.py --mode failover, repeated until every replica was the target ==')
hook = 'scripts/stop-one.cmd' if os.name == 'nt' else 'scripts/stop-one.sh'
replicas = api_replicas()
targeted = set()
for attempt in range(1, 7):
before = set(api_replicas())
_, code, seconds = run(PY + ['tests/resilience.py', '--mode', 'failover', '--action-script', hook, '--base-url', BASE], check=False)
stopped = before - set(api_replicas())
for cid in stopped:
out('attempt %d: stopped container %s (%s), State: %s, ExitCode %s' % (
attempt, cid, replicas.get(cid), inspect(cid, '{{.State.Status}}'), inspect(cid, '{{.State.ExitCode}}')))
verdict('public failover test passes (attempt %d)' % attempt, code == 0 and len(stopped) == 1, '%.1f s' % seconds)
targeted |= stopped
compose('up', '-d', '--wait', quiet=True)
if not wait_replicas(len(replicas)):
raise Stop('replicas did not come back')
if targeted >= set(replicas):
break
verdict('every replica was stopped by the hook at least once', targeted >= set(replicas),
', '.join(sorted(replicas[c] for c in targeted if c in replicas)))
def section_experiment():
out('== Experiment: stop, then kill, each replica in turn under load; restore before the next one ==')
replicas = api_replicas()
count = len(replicas)
load = Load()
poller = StatsPoller()
poller.start()
load.start()
rows = []
try:
time.sleep(5)
for mode in ('stop', 'kill'):
for cid, name in sorted(replicas.items(), key=lambda item: item[1]):
address = inspect(cid, '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}')
slot = poller.slot_of(address)
base_start = time.monotonic() - 5
baseline = load.window(base_start, time.monotonic())
t0 = time.monotonic()
_, _, command_seconds = run(['docker', mode, cid], quiet=True)
time.sleep(8)
t1 = time.monotonic()
during = load.window(t0, t1)
gap = load.max_gap(t0, t1)
detected = poller.first_change(slot, ('DOWN', 'MAINT', 'NOLB'), t0)
last_served = load.last_served_by(cid, t0)
run(['docker', 'start', cid], quiet=True)
t2 = time.monotonic()
back = None
while time.monotonic() - t2 < 60 and back is None:
time.sleep(0.2)
back = load.first_served_by(cid, t2)
time.sleep(3)
after = load.window(back or t2, time.monotonic())
row = {
'replica': name, 'lb_slot': slot, 'action': 'docker ' + mode, 'command_s': round(command_seconds, 2),
'baseline_ok_rps': baseline['ok_rps'], 'during_ok_rps': during['ok_rps'],
'errors_during': during['errors'], 'requests_during': during['requests'],
'max_gap_s': round(gap, 2),
'lb_marked_down_s': round(detected - t0, 2) if detected else None,
'last_served_s': round(last_served - t0, 2) if last_served else None,
'back_in_rotation_s': round(back - t2, 2) if back else None,
'after_ok_rps': after['ok_rps'], 'errors_after': after['errors'],
}
rows.append(row)
out(json.dumps(row, ensure_ascii=False))
if not wait_replicas(count):
raise Stop('replicas did not come back after %s' % name)
time.sleep(2)
finally:
load.stop()
poller.stop_event.set()
acknowledged, present, duplicates = load.verify()
out()
out('%-16s %-12s %6s %8s %8s %7s %8s %8s %8s %8s' % (
'replica', 'action', 'cmd,s', 'rps0', 'rps', 'errors', 'gap,s', 'down,s', 'back,s', 'rps1'))
for r in rows:
out('%-16s %-12s %6s %8s %8s %7s %8s %8s %8s %8s' % (
r['replica'], r['action'], r['command_s'], r['baseline_ok_rps'], r['during_ok_rps'], r['errors_during'],
r['max_gap_s'], r['lb_marked_down_s'], r['back_in_rotation_s'], r['after_ok_rps']))
out('acknowledged writes: %d, found in history: %d, duplicates: %d' % (acknowledged, present, duplicates))
stops = [r for r in rows if r['action'] == 'docker stop']
kills = [r for r in rows if r['action'] == 'docker kill']
verdict('graceful stop of each replica: no client errors, LB removes it within 3 s',
len(stops) == count and all(r['errors_during'] == 0 and r['lb_marked_down_s'] is not None
and r['lb_marked_down_s'] <= 3 for r in stops))
verdict('kill of each replica: LB removes it within 3 s, writes go on within 10 s',
len(kills) == count and all(r['lb_marked_down_s'] is not None and r['lb_marked_down_s'] <= 3
and r['max_gap_s'] <= 10 for r in kills))
verdict('every replica comes back into rotation after docker start', all(r['back_in_rotation_s'] is not None for r in rows))
verdict('no acknowledged write is lost or duplicated (retries reuse the key)', acknowledged == present and duplicates == 0)
def section_rolling():
out('== Rolling update under load: one replica at a time, new image, migrations once ==')
replicas = api_replicas()
count = len(replicas)
old_image = inspect('mtusi-messenger:lab3', '{{.Id}}')
version = 'rolling-%d' % int(time.time())
env = dict(os.environ, APP_VERSION=version)
compose('build', 'api', env=env, quiet=True)
new_image = inspect('mtusi-messenger:lab3', '{{.Id}}')
out('image before %s, after %s, APP_VERSION=%s' % (old_image[7:19], new_image[7:19], version))
migrate = compose('run', '--rm', '--no-deps', 'migrate', env=env)[0]
load = Load()
load.start()
started = time.monotonic()
steps = []
try:
time.sleep(3)
for old in sorted(replicas, key=lambda cid: replicas[cid]):
known = set(api_replicas(all_states=True))
compose('up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=%d' % (count + 1), 'api', env=env, quiet=True)
new = [cid for cid in api_replicas() if cid not in known]
if len(new) != 1 or not wait_replicas(count + 1):
raise Stop('new replica did not become ready')
run(['docker', 'stop', old], quiet=True)
run(['docker', 'rm', old], quiet=True)
steps.append('%s (%s) -> %s' % (replicas[old], old, new[0]))
out('replaced ' + steps[-1])
time.sleep(3)
finally:
load.stop()
stats = load.window(started, time.monotonic())
acknowledged, present, duplicates = load.verify()
final = api_replicas()
images = {cid: inspect(cid, '{{.Image}}') for cid in final}
versions = {cid: silent(['docker', 'exec', cid, 'printenv', 'APP_VERSION']) for cid in final}
out('during the update: %s' % json.dumps(stats))
out('final replicas: ' + ', '.join('%s %s version=%s' % (final[c], c, versions[c]) for c in sorted(final)))
out('acknowledged writes: %d, found in history: %d, duplicates: %d' % (acknowledged, present, duplicates))
verdict('migrations are applied once and the change is backward compatible', 'applied_now=0' in migrate)
verdict('every replica was replaced one by one by the new image under load',
len(steps) == count and len(final) == count and set(images.values()) == {new_image}
and set(versions.values()) == {version})
verdict('no client errors and no lost or duplicated writes during the rolling update',
stats['errors'] == 0 and acknowledged == present and duplicates == 0,
'%d requests, %.1f ok RPS' % (stats['requests'], stats['ok_rps']))
def section_persistence():
out('== Full restart: public tests/resilience.py --mode persistence with the restart hook ==')
hook = 'scripts/restart.cmd' if os.name == 'nt' else 'scripts/restart.sh'
services = {name: cid for cid, name in api_replicas().items()}
services.update({s: container(s) for s in ('postgres', 'valkey', 'lb')})
before = {name: inspect(cid, '{{.State.StartedAt}}') for name, cid in services.items()}
volumes = ['%s_pgdata' % PROJECT, '%s_valkeydata' % PROJECT]
volumes_before = run(['docker', 'volume', 'inspect', '-f', '{{.Name}} {{.CreatedAt}}'] + volumes)[0]
_, code, seconds = run(PY + ['tests/resilience.py', '--mode', 'persistence', '--action-script', hook, '--base-url', BASE], check=False)
after = {name: inspect(cid, '{{.State.StartedAt}}') for name, cid in services.items()}
volumes_after = run(['docker', 'volume', 'inspect', '-f', '{{.Name}} {{.CreatedAt}}'] + volumes)[0]
for name in sorted(before):
out('%-18s StartedAt %s -> %s' % (name, before[name][11:23], after[name][11:23]))
restarted = all(before[name] != after[name] for name in before)
verdict('persistence test passes after restarting every replica, postgres, valkey and lb with the same volumes',
code == 0 and restarted and volumes_before == volumes_after, 'hook %s, %.1f s' % (hook, seconds))
SECTIONS = {
'stack': section_stack,
'migrations': section_migrations,
'balancing': section_balancing,
'idempotency': section_idempotency,
'rollback': section_rollback,
'race': section_race,
'pool': section_pool,
'timeouts': section_timeouts,
'logs': section_logs,
'expiry': section_expiry,
'valkey-down': section_valkey_down,
'postgres-down': section_postgres_down,
'failover': section_failover,
'experiment': section_experiment,
'rolling': section_rolling,
'persistence': section_persistence,
}
def main():
parser = argparse.ArgumentParser(description='Lab 3 infrastructure checks; creates synthetic users and messages')
parser.add_argument('--only', nargs='+', choices=sorted(SECTIONS), help='run only these sections')
parser.add_argument('--output', default=None, help='also write the transcript to this file')
args = parser.parse_args()
sys.stdout.reconfigure(errors='replace')
out('# %s UTC, python %s, %s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()), sys.version.split()[0], sys.platform))
out('# ' + silent(['docker', 'version', '--format', 'docker {{.Server.Version}}']))
if not wait_ready(seconds=30):
out('API is not ready on %s: start the stand with docker compose up -d --build --wait' % BASE)
return 2
for name in args.only or SECTIONS:
try:
SECTIONS[name]()
except (Stop, KeyError, TypeError, ValueError) as error:
verdict('section %s completed' % name, False, str(error) or type(error).__name__)
if not wait_ready(seconds=60):
verdict('stand is ready after section %s' % name, False)
break
out('== Summary ==')
for name, ok in results:
out('%s %s' % ('PASS' if ok else 'FAIL', name))
failed = [name for name, ok in results if not ok]
out('RESULT: %s' % ('FAIL' if failed else 'PASS'))
if args.output:
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
Path(args.output).write_text('\n'.join(lines) + '\n', encoding='utf-8')
return 1 if failed else 0
if __name__ == '__main__':
try:
sys.exit(main())
except FileNotFoundError:
print('docker CLI was not found: install Docker and make sure it is on PATH')
sys.exit(2)
+10
View File
@@ -0,0 +1,10 @@
@echo off
rem Windows twin of scripts/restart.sh: tests/resilience.py starts the hook directly,
rem and Windows cannot execute a .sh file. Same actions, volumes are kept.
setlocal
cd /d "%~dp0.."
docker compose stop api || exit /b 1
docker compose restart postgres valkey || exit /b 1
docker compose start api || exit /b 1
docker compose restart lb || exit /b 1
exit /b 0
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# Hook for: make test-persistence ACTION_SCRIPT=scripts/restart.sh
# Restarts the whole stand: all API replicas, PostgreSQL, Valkey and the load balancer,
# keeping the named volumes: no "down -v", no FLUSHALL, no re-seed.
# The test itself waits for API readiness through the load balancer afterwards.
set -eu
cd "$(dirname "$0")/.."
docker compose stop api
docker compose restart postgres valkey
docker compose start api
docker compose restart lb
+19
View File
@@ -0,0 +1,19 @@
@echo off
rem Windows twin of scripts/stop-one.sh: tests/resilience.py starts the hook directly,
rem and Windows cannot execute a .sh file. Stops ONE api replica by X-Instance-Id (container ID).
setlocal
if "%TARGET_INSTANCE_ID%"=="" (
echo TARGET_INSTANCE_ID is not set 1>&2
exit /b 2
)
cd /d "%~dp0.."
set PROJECT=%COMPOSE_PROJECT_NAME%
if "%PROJECT%"=="" set PROJECT=mtusi-lab3
set ID=
for /f %%i in ('docker ps -q --filter "id=%TARGET_INSTANCE_ID%" --filter "label=com.docker.compose.project=%PROJECT%" --filter "label=com.docker.compose.service=api"') do set ID=%%i
if "%ID%"=="" (
echo TARGET_INSTANCE_ID is not a running api replica of %PROJECT% 1>&2
exit /b 1
)
docker stop %ID% >nul || exit /b 1
exit /b 0
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Hook for: make test-failover ACTION_SCRIPT=scripts/stop-one.sh
# Stops exactly ONE API replica and leaves it stopped. TARGET_INSTANCE_ID is the X-Instance-Id
# of the replica, which is its container hostname = short container ID. The hook checks that
# the ID belongs to a running "api" container of this compose project before stopping it.
# docker stop sends SIGTERM: the replica reports not ready, HAProxy removes it, then it exits.
# Restore afterwards: docker compose up -d (or docker start <id>)
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
cd "$(dirname "$0")/.."
project="${COMPOSE_PROJECT_NAME:-mtusi-lab3}"
id=$(docker ps -q --filter "id=$TARGET_INSTANCE_ID" \
--filter "label=com.docker.compose.project=$project" \
--filter "label=com.docker.compose.service=api")
if [ -z "$id" ]; then
echo "TARGET_INSTANCE_ID is not a running api replica of $project" >&2
exit 1
fi
docker stop "$id" >/dev/null
+1
View File
@@ -0,0 +1 @@
"""In-memory мессенджер, лабораторная 1. Только стандартная библиотека Python."""
+92
View File
@@ -0,0 +1,92 @@
"""Точка входа API: python -m messenger."""
import logging
import signal
import sys
import threading
import time
from .config import load_config
from .db import Repository, create_pool
from .server import MessengerServer
from .sessions import SessionStore
log = logging.getLogger('messenger')
# Как часто реплика удаляет ключи идемпотентности старше срока хранения.
CLEANUP_INTERVAL = 600
def cleanup_idempotency_keys(repo, ttl, stop):
"""Фоновая очистка. Каждая реплика делает одно и то же; повторный DELETE безвреден."""
while not stop.wait(CLEANUP_INTERVAL):
try:
deleted = repo.delete_expired_idempotency_keys(ttl)
log.info('event=idempotency_cleanup deleted=%d', deleted)
except Exception as error: # очистка не должна останавливать реплику
log.warning('event=idempotency_cleanup_failed error=%s', type(error).__name__)
def main():
config = load_config()
logging.Formatter.converter = time.gmtime # время в логах — UTC
logging.basicConfig(
stream=sys.stdout,
level=config.log_level,
format='%(asctime)s.%(msecs)03dZ %(levelname)s %(message)s',
datefmt='%Y-%m-%dT%H:%M:%S',
)
# Пул открывается в фоне: если БД ещё не готова, API всё равно стартует,
# а /health/ready отвечает 503, пока соединение не появится.
pool = create_pool(config.database_url, config.db_pool_size)
pool.open(wait=False)
sessions = SessionStore(config.cache_url, config.session_ttl)
repo = Repository(pool)
try:
server = MessengerServer((config.host, config.port), repo, sessions, config.instance_id, config.idempotency_ttl)
except OSError as error:
log.error('event=bind_failed host=%s port=%d error=%s', config.host, config.port, error)
return 1
# Обработчик сигнала только запоминает номер: всю остановку делает главный поток.
received = []
def on_signal(signum, _frame):
received.append(signum)
for name in ('SIGTERM', 'SIGINT', 'SIGBREAK'): # SIGBREAK есть только в Windows
if hasattr(signal, name):
signal.signal(getattr(signal, name), on_signal)
stop_cleanup = threading.Event()
threading.Thread(target=cleanup_idempotency_keys, args=(repo, config.idempotency_ttl, stop_cleanup),
name='idempotency-cleanup', daemon=True).start()
threading.Thread(target=server.serve_forever, name='accept-loop', daemon=True).start()
log.info('event=started instance=%s version=%s host=%s port=%d env=%s session_ttl_s=%d db_pool_max=%d '
'drain_delay_s=%g shutdown_timeout_s=%g', config.instance_id, config.version, config.host, config.port,
config.env, config.session_ttl, config.db_pool_size, config.drain_delay, config.shutdown_timeout)
while not received:
time.sleep(0.1)
started = time.monotonic()
log.info('event=shutdown_started signal=%s', signal.Signals(received[0]).name)
# 1. Реплика объявляет себя неготовой, но ещё обслуживает запросы: балансировщик проверяет
# /health/ready каждую секунду и после двух неудач (около 2 с) перестаёт слать сюда трафик.
server.begin_not_ready()
time.sleep(config.drain_delay)
# 2. Приём закрывается. Запросы на уже открытых соединениях получают 503.
server.begin_drain()
server.shutdown()
server.server_close()
# 3. Начатые запросы дорабатывают. Секунда остаётся на закрытие соединений с хранилищами.
remaining = config.shutdown_timeout - 1 - (time.monotonic() - started)
clean = server.wait_idle(max(remaining, 0))
stop_cleanup.set()
pool.close(timeout=1)
sessions.close()
log.info('event=shutdown_finished clean=%s duration_ms=%.0f', clean, (time.monotonic() - started) * 1000)
return 0 if clean else 1
if __name__ == '__main__':
sys.exit(main())
+84
View File
@@ -0,0 +1,84 @@
"""Конфигурация из переменных окружения и файлов секретов (см. .env.example и compose.yaml)."""
import os
import socket
from collections import namedtuple
Config = namedtuple('Config', 'host port env log_level shutdown_timeout drain_delay session_ttl idempotency_ttl '
'db_pool_size database_url cache_url instance_id version')
LOG_LEVELS = ('DEBUG', 'INFO', 'WARNING', 'ERROR')
# Заявленный срок остановки по SIGTERM — не более 10 секунд.
MAX_SHUTDOWN_TIMEOUT = 10.0
MAX_SESSION_TTL = 30 * 24 * 3600
# Контракт: результат идемпотентного запроса хранится не меньше 24 часов.
MIN_IDEMPOTENCY_TTL = 24 * 3600
def _environ(environ):
# strip(): .env из Windows может принести в значение символ \r.
return {name: value.strip() for name, value in (os.environ if environ is None else environ).items()}
def read_secret(name, environ=None):
"""Секрет из файла, путь к которому в NAME_FILE (секреты Docker), или из NAME для отладки.
Значение секрета никогда не попадает в сообщения об ошибках и в логи.
"""
environ = _environ(environ)
path = environ.get(name + '_FILE')
if path:
try:
with open(path, encoding='utf-8') as file:
value = file.read().strip()
except OSError as error:
raise SystemExit('Не удалось прочитать файл из %s_FILE: %s' % (name, error.strerror))
else:
value = environ.get(name, '')
if not value:
raise SystemExit('Нужен %s_FILE (путь к файлу секрета) или %s' % (name, name))
return value
def _integer(environ, name, default, low, high):
try:
value = int(environ.get(name, str(default)))
except ValueError:
raise SystemExit('%s должен быть целым числом' % name)
if not low <= value <= high:
raise SystemExit('%s должен быть в диапазоне %d..%d' % (name, low, high))
return value
def load_config(environ=None):
environ = _environ(environ)
try:
shutdown_timeout = float(environ.get('APP_SHUTDOWN_TIMEOUT', '8'))
drain_delay = float(environ.get('APP_DRAIN_DELAY', '3'))
except ValueError:
raise SystemExit('APP_SHUTDOWN_TIMEOUT и APP_DRAIN_DELAY должны быть числами')
if not 0 < shutdown_timeout <= MAX_SHUTDOWN_TIMEOUT:
raise SystemExit('APP_SHUTDOWN_TIMEOUT должен быть больше 0 и не больше 10 секунд')
# Задержка вывода из балансировщика входит в общий срок остановки, и на сами запросы
# должно остаться время.
if not 0 <= drain_delay <= shutdown_timeout - 2:
raise SystemExit('APP_DRAIN_DELAY должен быть от 0 до APP_SHUTDOWN_TIMEOUT - 2 секунд')
log_level = environ.get('APP_LOG_LEVEL', 'INFO').upper()
if log_level not in LOG_LEVELS:
raise SystemExit('APP_LOG_LEVEL должен быть одним из: ' + ', '.join(LOG_LEVELS))
return Config(
host=environ.get('APP_HOST', '0.0.0.0'),
port=_integer(environ, 'APP_PORT', 8080, 1, 65535),
env=environ.get('APP_ENV', 'lab'),
log_level=log_level,
shutdown_timeout=shutdown_timeout,
drain_delay=drain_delay,
session_ttl=_integer(environ, 'SESSION_TTL_SECONDS', 3600, 1, MAX_SESSION_TTL),
idempotency_ttl=_integer(environ, 'IDEMPOTENCY_TTL_SECONDS', MIN_IDEMPOTENCY_TTL,
MIN_IDEMPOTENCY_TTL, MAX_SESSION_TTL),
db_pool_size=_integer(environ, 'DB_POOL_SIZE', 10, 1, 50),
database_url=read_secret('DATABASE_URL', environ),
cache_url=read_secret('CACHE_URL', environ),
# X-Instance-Id: в Docker hostname контейнера — короткий ID, по нему хук находит реплику.
instance_id=environ.get('INSTANCE_ID') or socket.gethostname(),
version=environ.get('APP_VERSION', 'dev'),
)
+245
View File
@@ -0,0 +1,245 @@
"""Доступ к PostgreSQL: ограниченный пул соединений, таймауты, только параметризованные запросы.
Значения всегда передаются отдельно от текста SQL (%s), поэтому SQL-инъекция невозможна.
Каждый метод — одна транзакция: при любой ошибке внутри неё всё откатывается.
"""
import logging
import uuid
from contextlib import contextmanager
import psycopg
from psycopg import errors
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .errors import Unavailable
from .timeutil import format_time, from_micros, to_micros
log = logging.getLogger('messenger')
# Таймауты на стороне сервера БД: долгий запрос, ожидание блокировки и брошенная транзакция
# прерываются, а не держат соединение из пула бесконечно.
SESSION_OPTIONS = '-c statement_timeout=5000 -c lock_timeout=3000 -c idle_in_transaction_session_timeout=10000'
MEMBER_IDS = 'array(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids'
class UsernameTaken(Exception):
pass
class UnknownMember(Exception):
pass
class IdempotencyConflict(Exception):
"""Тот же Idempotency-Key уже использован с другим телом запроса."""
def create_pool(database_url, max_size):
return ConnectionPool(
database_url,
min_size=1,
max_size=max_size, # не больше max_size соединений с БД на процесс
timeout=3, # ждать свободное соединение не дольше 3 с, затем 503
max_waiting=100, # очередь ожидающих запросов ограничена
check=ConnectionPool.check_connection, # оборванное соединение (рестарт БД) не выдаётся
kwargs={
'connect_timeout': 3,
'application_name': 'messenger-api',
'options': SESSION_OPTIONS,
'row_factory': dict_row,
},
name='messenger',
open=False,
)
def _user(row):
return {'id': str(row['id']), 'username': row['username'], 'display_name': row['display_name'],
'created_at': format_time(row['created_at'])}
def _chat(row):
return {'id': str(row['id']), 'title': row['title'], 'member_ids': [str(m) for m in row['member_ids']],
'created_at': format_time(row['created_at'])}
def _message(row):
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']),
'text': row['text'], 'created_at': format_time(row['created_at'])}
def _page(rows, limit, convert):
"""Из limit+1 строк: элементы страницы и ключ (created_at, id) последней, если есть продолжение."""
items = rows[:limit]
has_more = len(rows) > limit
next_key = (to_micros(items[-1]['created_at']), str(items[-1]['id'])) if has_more else None
return [convert(row) for row in items], next_key
def _after(key):
return from_micros(key[0]), uuid.UUID(key[1])
class Repository:
def __init__(self, pool):
self._pool = pool
@contextmanager
def _transaction(self):
"""Соединение из пула в транзакции: COMMIT при успехе, ROLLBACK при исключении."""
try:
with self._pool.connection() as conn:
yield conn
except psycopg.OperationalError as error:
# Нет соединения, пул исчерпан, истёк statement_timeout/lock_timeout — всё это 503.
raise Unavailable('postgres') from error
def ping(self):
with self._transaction() as conn:
conn.execute('SELECT 1')
# --- пользователи -------------------------------------------------------
def create_user(self, username, display_name, password_hash):
try:
with self._transaction() as conn:
row = conn.execute(
'INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s) '
'RETURNING id, username, display_name, created_at',
(uuid.uuid4(), username, display_name, password_hash),
).fetchone()
except errors.UniqueViolation:
# Уникальность username гарантирует индекс БД, поэтому гонка двух регистраций безопасна.
raise UsernameTaken
return _user(row)
def get_user(self, user_id):
with self._transaction() as conn:
row = conn.execute(
'SELECT id, username, display_name, created_at FROM users WHERE id = %s', (uuid.UUID(user_id),),
).fetchone()
return _user(row) if row else None
def get_credentials(self, username):
"""(пользователь, хеш пароля) или (None, None)."""
with self._transaction() as conn:
row = conn.execute(
'SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s',
(username,),
).fetchone()
return (_user(row), row['password_hash']) if row else (None, None)
# --- чаты ---------------------------------------------------------------
def create_chat(self, title, member_ids):
"""Чат и все участники одной транзакцией.
Неизвестный участник нарушает внешний ключ chat_members.user_id; тогда транзакция
откатывается целиком и уже вставленная строка chats тоже исчезает.
"""
chat_id = uuid.uuid4()
members = [uuid.UUID(member_id) for member_id in member_ids]
try:
with self._transaction() as conn:
row = conn.execute(
'INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING id, title, created_at', (chat_id, title),
).fetchone()
conn.execute(
'INSERT INTO chat_members (chat_id, user_id, position) '
'SELECT %s, member.user_id, member.ordinality - 1 '
'FROM unnest(%s::uuid[]) WITH ORDINALITY AS member(user_id, ordinality)',
(chat_id, members),
)
except errors.ForeignKeyViolation:
log.info('event=chat_rolled_back reason=unknown_member')
raise UnknownMember
return _chat(dict(row, member_ids=members))
def get_chat(self, chat_id, user_id):
"""Чат, если он есть и user_id в нём состоит; иначе None."""
with self._transaction() as conn:
row = conn.execute(
'SELECT c.id, c.title, c.created_at, ' + MEMBER_IDS + ' FROM chats c '
'WHERE c.id = %s AND EXISTS ('
' SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)',
(uuid.UUID(chat_id), uuid.UUID(user_id)),
).fetchone()
return _chat(row) if row else None
def list_chats(self, user_id, after, limit):
select = ('SELECT c.id, c.title, c.created_at, ' + MEMBER_IDS + ' '
'FROM chat_members me JOIN chats c ON c.id = me.chat_id WHERE me.user_id = %s ')
order = 'ORDER BY c.created_at, c.id LIMIT %s'
with self._transaction() as conn:
if after is None:
rows = conn.execute(select + order, (uuid.UUID(user_id), limit + 1)).fetchall()
else:
rows = conn.execute(select + 'AND (c.created_at, c.id) > (%s, %s) ' + order,
(uuid.UUID(user_id), *_after(after), limit + 1)).fetchall()
return _page(rows, limit, _chat)
# --- сообщения ----------------------------------------------------------
def add_message(self, chat_id, sender_id, text, key, request_hash, ttl_seconds):
"""Идемпотентная отправка: (сообщение, True если это повтор уже выполненного запроса).
Строка чата блокируется до конца транзакции. Поэтому, во-первых, сообщения одного чата
записываются по очереди и created_at растёт в порядке фиксации: читатель, идущий по
cursor, не пропустит сообщение, зафиксированное позже уже прочитанного. Во-вторых,
одновременные запросы с одним ключом (область ключа включает путь чата) тоже идут по
очереди, даже через разные реплики: второй увидит ключ первого и вернёт то же сообщение.
Ключ и сообщение фиксируются одной транзакцией; при ошибке не остаётся ни того, ни другого.
"""
chat = uuid.UUID(chat_id)
scope = (uuid.UUID(sender_id), 'POST', '/api/v1/chats/%s/messages' % chat_id, key)
with self._transaction() as conn:
conn.execute('SELECT 1 FROM chats WHERE id = %s FOR NO KEY UPDATE', (chat,))
stored = conn.execute(
'SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at '
'FROM idempotency_keys k JOIN messages m ON m.id = k.message_id '
'WHERE k.user_id = %s AND k.method = %s AND k.path = %s AND k.key = %s '
' AND k.created_at > clock_timestamp() - make_interval(secs => %s)',
scope + (ttl_seconds,),
).fetchone()
if stored:
if stored['request_hash'] != request_hash:
raise IdempotencyConflict
return _message(stored), True
row = conn.execute(
'INSERT INTO messages (id, chat_id, sender_id, text, created_at) '
'VALUES (%s, %s, %s, %s, GREATEST(clock_timestamp(), '
" (SELECT max(created_at) FROM messages WHERE chat_id = %s) + interval '1 microsecond')) "
'RETURNING id, chat_id, sender_id, text, created_at',
(uuid.uuid4(), chat, uuid.UUID(sender_id), text, chat),
).fetchone()
# Устаревшая запись с тем же ключом (старше срока хранения) заменяется новой.
conn.execute(
'INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, message_id) '
'VALUES (%s, %s, %s, %s, %s, %s) '
'ON CONFLICT (user_id, method, path, key) DO UPDATE SET request_hash = EXCLUDED.request_hash, '
' message_id = EXCLUDED.message_id, created_at = EXCLUDED.created_at',
scope + (request_hash, row['id']),
)
return _message(row), False
def delete_expired_idempotency_keys(self, ttl_seconds):
"""Удаляет ключи старше срока хранения; возвращает число удалённых."""
with self._transaction() as conn:
return conn.execute(
'DELETE FROM idempotency_keys WHERE created_at < clock_timestamp() - make_interval(secs => %s)',
(ttl_seconds,),
).rowcount
def list_messages(self, chat_id, after, limit):
"""Страница истории. Запрос совпадает по форме с индексом messages_chat_history_idx."""
select = 'SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s '
order = 'ORDER BY created_at, id LIMIT %s'
with self._transaction() as conn:
if after is None:
rows = conn.execute(select + order, (uuid.UUID(chat_id), limit + 1)).fetchall()
else:
rows = conn.execute(select + 'AND (created_at, id) > (%s, %s) ' + order,
(uuid.UUID(chat_id), *_after(after), limit + 1)).fetchall()
return _page(rows, limit, _message)
+29
View File
@@ -0,0 +1,29 @@
"""Ошибки, которые HTTP-слой превращает в ответы контракта."""
class ApiError(Exception):
"""Ответ с ошибкой в формате {"error": {...}}; challenge — значение WWW-Authenticate для 401."""
def __init__(self, status, code, message, challenge=None):
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.challenge = challenge
class Unavailable(Exception):
"""Хранилище (postgres или valkey) не ответило в срок; клиент получит 503."""
def __init__(self, dependency):
super().__init__(dependency)
self.dependency = dependency
def bad_request(message):
return ApiError(400, 'invalid_request', message)
def not_found():
# Чужой объект неотличим от несуществующего.
return ApiError(404, 'not_found', 'Объект не найден')
+26
View File
@@ -0,0 +1,26 @@
"""Проверка для Docker HEALTHCHECK: python -m messenger.healthcheck.
В slim-образе нет curl, поэтому готовность проверяется самим интерпретатором.
Код возврата 0 — контейнер healthy, 1 — unhealthy.
"""
import http.client
import os
import sys
def main():
try:
connection = http.client.HTTPConnection('127.0.0.1', int(os.environ.get('APP_PORT', '8080')), timeout=2)
try:
connection.request('GET', '/health/ready', headers={'Connection': 'close'})
response = connection.getresponse()
response.read() # дочитываем ответ, чтобы соединение закрылось штатно, а не обрывом
return 0 if response.status == 200 else 1
finally:
connection.close()
except (OSError, ValueError, http.client.HTTPException):
return 1
if __name__ == '__main__':
sys.exit(main())
+77
View File
@@ -0,0 +1,77 @@
"""Миграции схемы: python -m messenger.migrate.
Файлы migrations/NNNN_*.sql применяются по порядку номеров, каждый в своей транзакции.
Применённые версии и контрольные суммы записываются в schema_migrations, поэтому повторный
запуск ничего не дублирует. Изменение уже применённого файла останавливает запуск: менять
схему нужно новым файлом. Advisory lock не даёт двум процессам применять миграции одновременно.
"""
import hashlib
import logging
import sys
import time
from pathlib import Path
import psycopg
from .config import read_secret
log = logging.getLogger('messenger.migrate')
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / 'migrations'
LOCK_ID = 2026_0002 # произвольная константа для pg_advisory_lock
CREATE_TABLE = '''
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)'''
def _read(path):
# Окончания строк нормализуются: checkout в Windows (CRLF) не должен менять контрольную сумму.
sql = path.read_text(encoding='utf-8').replace('\r\n', '\n')
return sql, hashlib.sha256(sql.encode('utf-8')).hexdigest()
def migrate(database_url, directory=MIGRATIONS_DIR):
files = sorted(directory.glob('[0-9][0-9][0-9][0-9]_*.sql'))
if not files:
raise SystemExit('Нет файлов миграций в ' + str(directory))
applied_now = 0
with psycopg.connect(database_url, autocommit=True, connect_timeout=5) as conn:
conn.execute('SELECT pg_advisory_lock(%s)', (LOCK_ID,))
try:
conn.execute(CREATE_TABLE)
applied = dict(conn.execute('SELECT version, checksum FROM schema_migrations').fetchall())
for path in files:
version = path.stem
sql, checksum = _read(path)
if version in applied:
if applied[version] != checksum:
raise SystemExit('Миграция %s изменена после применения: добавьте новую вместо правки' % version)
continue
started = time.monotonic()
with conn.transaction():
conn.execute(sql)
conn.execute('INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)', (version, checksum))
applied_now += 1
log.info('event=migration_applied version=%s duration_ms=%.0f', version, (time.monotonic() - started) * 1000)
finally:
conn.execute('SELECT pg_advisory_unlock(%s)', (LOCK_ID,))
log.info('event=migrations_done applied_now=%d total=%d', applied_now, len(files))
def main():
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(levelname)s %(message)s')
try:
migrate(read_secret('DATABASE_URL'))
except psycopg.Error as error:
# Сообщения psycopg не содержат пароль, а первая строка объясняет причину.
log.error('event=migration_failed error=%s detail=%s', type(error).__name__, str(error).splitlines()[0][:300])
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
+50
View File
@@ -0,0 +1,50 @@
"""Хеширование паролей: Argon2id из библиотеки argon2-cffi.
Хеш хранит алгоритм, параметры и соль в одной строке вида $argon2id$v=19$m=...,t=...,p=...$соль$хеш.
"""
import secrets
import threading
from contextlib import contextmanager
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from .errors import Unavailable
# Минимальные параметры из OWASP Password Storage Cheat Sheet: 19 МиБ памяти, 2 прохода, 1 поток.
_hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1)
# Каждый расчёт занимает 19 МиБ памяти. Одновременно считаем не больше 4 хешей на процесс,
# чтобы пик памяти реплики был предсказуем при лимите контейнера (compose.yaml, 256 МБ).
# Остальные запросы ждут очереди; дольше 5 с — ответ 503 вместо бесконечного ожидания.
MAX_CONCURRENT_HASHES = 4
_slots = threading.BoundedSemaphore(MAX_CONCURRENT_HASHES)
# Хеш случайного пароля. Проверка против него для несуществующего username занимает
# столько же времени, сколько обычная: по задержке ответа нельзя узнать, есть ли пользователь.
_DUMMY_HASH = _hasher.hash(secrets.token_hex(16))
@contextmanager
def _slot():
if not _slots.acquire(timeout=5):
raise Unavailable('password-hashing')
try:
yield
finally:
_slots.release()
def hash_password(password):
with _slot():
return _hasher.hash(password)
def verify_password(password_hash, password):
"""True, если пароль подходит к хешу; при password_hash=None всегда False за то же время."""
with _slot():
try:
_hasher.verify(password_hash or _DUMMY_HASH, password)
except (VerificationError, InvalidHashError):
return False
return password_hash is not None
+369
View File
@@ -0,0 +1,369 @@
"""HTTP-слой: маршрутизация, аутентификация, ответы в формате контракта, логи запросов."""
import json
import logging
import re
import sys
import threading
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from . import validation
from .db import IdempotencyConflict, UnknownMember, UsernameTaken
from .errors import ApiError, Unavailable, bad_request, not_found
from .passwords import hash_password, verify_password
from .timeutil import format_time
log = logging.getLogger('messenger')
# Сообщение в 4000 символов даже в виде \uXXXX-последовательностей меньше 64 КиБ.
MAX_BODY_BYTES = 64 * 1024
# Тело до этого размера дочитывается ради аккуратного 413; больше — соединение просто закрывается.
MAX_DISCARD_BYTES = 1024 * 1024
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
CHAT = r'/api/v1/chats/(?P<chat_id>[^/]+)'
ROUTES = tuple((method, re.compile(pattern), handler) for method, pattern, handler in (
('GET', r'/health/live', '_live'),
('GET', r'/health/ready', '_ready'),
('POST', r'/api/v1/users', '_create_user'),
('GET', r'/api/v1/users/me', '_current_user'),
('POST', r'/api/v1/auth/sessions', '_create_session'),
('DELETE', r'/api/v1/auth/sessions/current', '_delete_session'),
('POST', r'/api/v1/chats', '_create_chat'),
('GET', r'/api/v1/chats', '_list_chats'),
('GET', CHAT, '_get_chat'),
('POST', CHAT + r'/messages', '_create_message'),
('GET', CHAT + r'/messages', '_list_messages'),
))
class MessengerServer(ThreadingHTTPServer):
"""Поток на соединение; считает выполняющиеся запросы для плавной остановки."""
# Потоки-демоны не держат процесс: срок остановки ограничивает wait_idle().
daemon_threads = True
# Очередь соединений по умолчанию (5) мала для десятков одновременных клиентов.
request_queue_size = 128
def __init__(self, address, repo, sessions, instance_id, idempotency_ttl):
super().__init__(address, RequestHandler)
self.repo = repo
self.sessions = sessions
self.instance_id = instance_id
self.idempotency_ttl = idempotency_ttl
self._state = threading.Condition()
self._active = 0
self._draining = False
self.ready = True
def begin_not_ready(self):
"""Первый шаг остановки: /health/ready отвечает 503, остальные запросы ещё обслуживаются.
Балансировщик видит это при следующих проверках и перестаёт присылать сюда запросы.
"""
self.ready = False
def try_begin_request(self):
"""False, если сервер уже останавливается и запрос принимать нельзя."""
with self._state:
if self._draining:
return False
self._active += 1
return True
def end_request(self):
with self._state:
self._active -= 1
self._state.notify_all()
def begin_drain(self):
with self._state:
self._draining = True
def wait_idle(self, timeout):
"""Ждёт завершения начатых запросов; True, если успели за timeout секунд."""
with self._state:
return self._state.wait_for(lambda: self._active == 0, timeout)
def handle_error(self, request, client_address):
# Обрыв соединения клиентом — обычная ситуация, а не ошибка сервера: без traceback.
error = sys.exc_info()[0]
level = logging.DEBUG if issubclass(error, ConnectionError) else logging.WARNING
log.log(level, 'event=connection_error error=%s', error.__name__)
class RequestHandler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
# Секунды ожидания данных от клиента: зависшее соединение не занимает поток вечно.
timeout = 15
def do_GET(self):
self._handle()
do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = do_OPTIONS = do_GET
# --- общий путь запроса -------------------------------------------------
def _handle(self):
started = time.monotonic()
self.request_id = uuid.uuid4().hex
self.user_id = '-'
path, _, query = self.path.partition('?')
status = 0 # 0 в логе: ответ отправить не удалось
accepted = self.server.try_begin_request()
try:
if accepted:
status, payload, headers = self._process(path, query)
else:
self.close_connection = True
status, payload, headers = self._error(ApiError(503, 'unavailable', 'Сервер завершает работу'))
self._send(status, payload, headers)
except OSError:
status = 0
self.close_connection = True
finally:
if accepted:
self.server.end_request()
# В лог попадают только метаданные: тела запросов, тексты сообщений, пароли и токены не пишутся.
log.log(
logging.DEBUG if path.startswith('/health/') else logging.INFO,
'request_id=%s method=%s path=%s status=%d duration_ms=%.1f user_id=%s',
self.request_id, self.command, re.sub(r'[^\x21-\x7e]', '?', path)[:200], status,
(time.monotonic() - started) * 1000, self.user_id,
)
def _process(self, path, query):
"""(статус, тело или None, дополнительные заголовки)."""
try:
body = self._read_body()
for method, pattern, handler in ROUTES:
match = pattern.fullmatch(path)
if match and method == self.command:
params = parse_qs(query, keep_blank_values=True)
status, payload = getattr(self, handler)(body, params, **match.groupdict())
return status, payload, ()
raise ApiError(404, 'not_found', 'Маршрут не найден')
except ApiError as error:
return self._error(error)
except Unavailable as error:
log.warning('event=dependency_unavailable request_id=%s dependency=%s error=%s',
self.request_id, error.dependency, type(error.__cause__).__name__)
return self._error(ApiError(503, 'unavailable', 'Сервис временно недоступен: ' + error.dependency))
except Exception:
log.exception('event=unhandled_error request_id=%s', self.request_id)
return self._error(ApiError(500, 'internal_error', 'Внутренняя ошибка сервера'))
def _read_body(self):
"""Читает тело целиком до маршрутизации, чтобы keep-alive поток не сбился."""
header = self.headers.get('Content-Length')
if header is None:
if self.headers.get('Transfer-Encoding'):
self.close_connection = True
raise bad_request('Нужен заголовок Content-Length')
return b''
if not re.fullmatch(r'[0-9]{1,18}', header):
self.close_connection = True
raise bad_request('Некорректный Content-Length')
length = int(header)
if length > MAX_BODY_BYTES:
self.close_connection = True
if length <= MAX_DISCARD_BYTES:
self._discard(length)
raise ApiError(413, 'payload_too_large', 'Тело запроса больше %d байт' % MAX_BODY_BYTES)
try:
body = self.rfile.read(length)
except OSError: # таймаут или обрыв соединения
body = b''
if len(body) != length:
self.close_connection = True
raise bad_request('Тело запроса получено не полностью')
return body
def _discard(self, remaining):
"""Дочитывает слишком большое тело по частям, не храня его в памяти.
Если закрыть соединение с непрочитанными данными, клиент получит обрыв
вместо ответа 413.
"""
try:
while remaining > 0:
chunk = self.rfile.read(min(remaining, 64 * 1024))
if not chunk:
break
remaining -= len(chunk)
except OSError:
pass
def _error(self, error):
payload = {'error': {'code': error.code, 'message': error.message, 'request_id': self.request_id}}
headers = (('WWW-Authenticate', error.challenge),) if error.challenge else ()
return error.status, payload, headers
def _send(self, status, payload, headers=()):
"""Ответ с JSON-телом; payload=None — ответ без тела (204)."""
body = b'' if payload is None else json.dumps(payload, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
self.send_response(status)
if payload is not None:
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.send_header('X-Request-Id', self.request_id)
# Какая реплика ответила: имя контейнера, стабильно для жизни процесса.
self.send_header('X-Instance-Id', self.server.instance_id)
for name, value in headers:
self.send_header(name, value)
if self.close_connection:
self.send_header('Connection', 'close')
self.end_headers()
if body and self.command != 'HEAD':
self.wfile.write(body)
def send_error(self, code, message=None, explain=None):
"""Ошибки разбора HTTP (до маршрутизации) — тоже в общем формате ошибок."""
self.request_id = uuid.uuid4().hex
self.close_connection = True
if code == 501: # метод, которого нет в API
error = ApiError(404, 'not_found', 'Маршрут не найден')
else:
error = bad_request('Некорректный HTTP-запрос')
self._send(*self._error(error))
log.info('request_id=%s event=http_parse_error http_status=%d status=%d', self.request_id, code, error.status)
def version_string(self):
return 'messenger' # заголовок Server без версии Python
def log_request(self, code='-', size='-'):
pass # запрос логируется один раз в _handle
def log_message(self, format, *args):
log.debug('event=http_server detail=%s', format % args)
# --- общие проверки -----------------------------------------------------
def _authenticate(self):
"""user_id владельца Bearer-токена. X-User-Id и Basic здесь не принимаются.
Если Valkey недоступен, sessions.user_id бросает Unavailable и клиент получает 503:
запрос не продолжается как анонимный.
"""
token = validation.parse_bearer(self.headers.get('Authorization'))
user_id = self.server.sessions.user_id(token) if token else None
if user_id is None:
raise ApiError(401, 'unauthorized', 'Нужен действующий токен: Authorization: Bearer <token>',
challenge=BEARER_CHALLENGE)
self.token = token
self.user_id = user_id
return user_id
def _accessible_chat(self, user_id, raw_chat_id):
chat_id = validation.parse_uuid(raw_chat_id)
if chat_id is None:
raise bad_request('chat_id должен быть UUID')
chat = self.server.repo.get_chat(chat_id, user_id)
if chat is None:
raise not_found()
return chat
def _json_body(self, body):
if self.headers.get_content_type() != 'application/json':
raise bad_request('Content-Type должен быть application/json')
return body
# --- обработчики маршрутов ----------------------------------------------
def _live(self, body, query):
return 200, {'status': 'ok'}
def _ready(self, body, query):
# После SIGTERM реплика сначала перестаёт быть готовой, чтобы балансировщик её исключил.
if not self.server.ready:
raise ApiError(503, 'unavailable', 'Реплика завершает работу')
# Обязательный путь API требует обоих хранилищ: без БД нет данных, без Valkey — сессий.
self.server.repo.ping()
self.server.sessions.ping()
return 200, {'status': 'ok'}
def _create_user(self, body, query):
username, display_name, password = validation.parse_create_user(self._json_body(body))
try:
return 201, self.server.repo.create_user(username, display_name, hash_password(password))
except UsernameTaken:
raise ApiError(409, 'conflict', 'Пользователь с таким username уже существует')
def _create_session(self, body, query):
"""Вход: только Authorization: Basic. Ответ 401 одинаковый для любой ошибки входа."""
if body:
raise bad_request('Тело не нужно: логин и пароль передаются в Authorization: Basic')
credentials = validation.parse_basic(self.headers.get('Authorization'))
user = None
if credentials:
username, password = credentials
user, password_hash = self.server.repo.get_credentials(username)
# Для несуществующего username проверка идёт против фиктивного хеша за то же время.
if not verify_password(password_hash, password):
user = None
if user is None:
raise ApiError(401, 'unauthorized', 'Неверный логин или пароль', challenge=BASIC_CHALLENGE)
token, expires_at = self.server.sessions.create(user['id'])
self.user_id = user['id']
return 201, {'token': token, 'token_type': 'Bearer', 'expires_at': format_time(expires_at), 'user': user}
def _delete_session(self, body, query):
self._authenticate()
if not self.server.sessions.revoke(self.token):
# Сессия истекла между проверкой и удалением.
raise ApiError(401, 'unauthorized', 'Сессия уже недействительна', challenge=BEARER_CHALLENGE)
return 204, None
def _current_user(self, body, query):
user = self.server.repo.get_user(self._authenticate())
if user is None:
raise ApiError(401, 'unauthorized', 'Пользователь сессии не найден', challenge=BEARER_CHALLENGE)
return 200, user
def _create_chat(self, body, query):
user_id = self._authenticate()
title, member_ids = validation.parse_create_chat(self._json_body(body))
if user_id not in member_ids:
raise bad_request('member_ids должен включать вызывающего пользователя')
try:
return 201, self.server.repo.create_chat(title, member_ids)
except UnknownMember:
raise bad_request('member_ids содержит неизвестного пользователя')
def _list_chats(self, body, query):
user_id = self._authenticate()
scope = 'chats:' + user_id
limit = validation.parse_limit(query)
after = validation.parse_cursor(query, scope)
items, next_key = self.server.repo.list_chats(user_id, after, limit)
return 200, {'items': items, 'next_cursor': validation.encode_cursor(scope, next_key)}
def _get_chat(self, body, query, chat_id):
return 200, self._accessible_chat(self._authenticate(), chat_id)
def _create_message(self, body, query, chat_id):
# Повтор с тем же ключом снова проходит аутентификацию и проверку доступа.
user_id = self._authenticate()
chat = self._accessible_chat(user_id, chat_id)
key = validation.parse_idempotency_key(self.headers.get('Idempotency-Key'))
text = validation.parse_create_message(self._json_body(body))
try:
message, replayed = self.server.repo.add_message(
chat['id'], user_id, text, key, validation.request_fingerprint(text), self.server.idempotency_ttl)
except IdempotencyConflict:
raise ApiError(409, 'conflict', 'Этот Idempotency-Key уже использован с другим телом запроса')
if replayed:
log.info('event=idempotent_replay request_id=%s message_id=%s', self.request_id, message['id'])
return 201, message
def _list_messages(self, body, query, chat_id):
chat = self._accessible_chat(self._authenticate(), chat_id)
scope = 'messages:' + chat['id']
limit = validation.parse_limit(query)
after = validation.parse_cursor(query, scope)
items, next_key = self.server.repo.list_messages(chat['id'], after, limit)
return 200, {'items': items, 'next_cursor': validation.encode_cursor(scope, next_key)}
+81
View File
@@ -0,0 +1,81 @@
"""Сессии в Valkey — единственное хранилище сессий.
Ключ: session:<sha256 от токена>, значение: JSON с user_id и сроком. Срок задаётся абсолютным
временем (PXAT), поэтому перезапуск ничего не продлевает. Сохранность при рестарте
обеспечивает AOF с fsync на каждую запись (infra/valkey/valkey.conf).
"""
import hashlib
import json
import secrets
import time
from contextlib import contextmanager
import valkey
from valkey.backoff import NoBackoff
from valkey.retry import Retry
from .errors import Unavailable
from .timeutil import from_micros
@contextmanager
def _valkey_errors():
# Любая ошибка Valkey (нет соединения, таймаут, загрузка AOF после рестарта, нехватка памяти)
# превращается в 503. Запрос не продолжается как анонимный и не считается доверенным.
try:
yield
except valkey.exceptions.ValkeyError as error:
raise Unavailable('valkey') from error
class SessionStore:
def __init__(self, url, ttl_seconds):
self.ttl_seconds = ttl_seconds
self._pool = valkey.BlockingConnectionPool.from_url(
url,
max_connections=20, # не больше 20 соединений на процесс
timeout=1, # ждать свободное соединение не дольше 1 с
socket_connect_timeout=1, # подключение и ответ — не дольше 1 с
socket_timeout=1,
retry=Retry(NoBackoff(), 1), # один повтор: переподключиться после рестарта Valkey
decode_responses=True,
)
self._client = valkey.Valkey(connection_pool=self._pool)
@staticmethod
def _key(token):
# В Valkey хранится только хеш токена: копия базы не даёт готовых токенов.
return 'session:' + hashlib.sha256(token.encode('ascii')).hexdigest()
def create(self, user_id):
"""Новая сессия: (токен, срок действия как datetime)."""
token = secrets.token_urlsafe(32) # 32 случайных байта = 256 бит
expires_ms = int(time.time() * 1000) + self.ttl_seconds * 1000
value = json.dumps({'user_id': user_id, 'expires_at_ms': expires_ms})
with _valkey_errors():
self._client.set(self._key(token), value, pxat=expires_ms)
return token, from_micros(expires_ms * 1000)
def user_id(self, token):
"""user_id владельца действующей сессии или None (неизвестна, отозвана, истекла)."""
with _valkey_errors():
raw = self._client.get(self._key(token))
if raw is None:
return None
session = json.loads(raw)
# Valkey удаляет ключ сам; проверка здесь — страховка на случай расхождения часов.
if session['expires_at_ms'] <= time.time() * 1000:
return None
return session['user_id']
def revoke(self, token):
"""Удаляет сессию; True, если она была."""
with _valkey_errors():
return self._client.delete(self._key(token)) == 1
def ping(self):
with _valkey_errors():
self._client.ping()
def close(self):
self._pool.disconnect()
+18
View File
@@ -0,0 +1,18 @@
"""Время в формате контракта: RFC 3339, UTC, микросекунды, суффикс Z."""
from datetime import datetime, timedelta, timezone
EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
MICROSECOND = timedelta(microseconds=1)
def format_time(value):
return value.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
def to_micros(value):
"""Целое число микросекунд с 1970 года: так время хранится в cursor без потери точности."""
return (value - EPOCH) // MICROSECOND
def from_micros(micros):
return EPOCH + timedelta(microseconds=micros)
+197
View File
@@ -0,0 +1,197 @@
"""Разбор и проверка входных данных по contracts/openapi.json и contracts/README.md."""
import base64
import binascii
import hashlib
import json
import re
from .errors import bad_request
USERNAME = re.compile(r'[a-z0-9_]{3,32}')
UUID = re.compile(r'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}')
LIMIT = re.compile(r'[0-9]{1,3}')
# Idempotency-Key из контракта: ASCII-символы [A-Za-z0-9._:-], от 1 до 128.
IDEMPOTENCY_KEY = re.compile(r'[A-Za-z0-9._:-]{1,128}')
# token68 из RFC 7235 с разумным ограничением длины.
BEARER_TOKEN = re.compile(r'[A-Za-z0-9\-._~+/]{1,512}=*')
DEFAULT_LIMIT = 50
MAX_LIMIT = 100
MAX_NAME = 100
MAX_MEMBERS = 100
MAX_TEXT = 4000
MIN_PASSWORD = 12
MAX_PASSWORD = 128
def parse_uuid(value):
"""UUID в каноническом виде (нижний регистр) или None."""
if isinstance(value, str) and UUID.fullmatch(value):
return value.lower()
return None
def _load_object(raw, fields):
"""JSON-объект ровно с полями fields: лишние и отсутствующие поля — ошибка."""
try:
data = json.loads(raw.decode('utf-8'))
except (ValueError, RecursionError):
raise bad_request('Тело запроса должно быть корректным JSON в UTF-8')
if not isinstance(data, dict):
raise bad_request('Тело запроса должно быть JSON-объектом')
for field in fields:
if field not in data:
raise bad_request('Отсутствует обязательное поле ' + field)
if len(data) != len(fields):
raise bad_request('В запросе есть лишние поля')
return data
def _string(data, field, max_length, min_length=1):
"""Строка из min_length..max_length code points, не только из пробельных символов."""
value = data[field]
if not isinstance(value, str):
raise bad_request('Поле %s должно быть строкой' % field)
if not value.strip():
raise bad_request('Поле %s не должно быть пустым' % field)
if not min_length <= len(value) <= max_length:
raise bad_request('Поле %s: от %d до %d символов' % (field, min_length, max_length))
# NUL нельзя сохранить в тексте PostgreSQL; одиночный суррогат (\ud800) нельзя вернуть в UTF-8.
if '\x00' in value:
raise bad_request('Поле %s содержит недопустимые символы' % field)
try:
value.encode('utf-8')
except UnicodeEncodeError:
raise bad_request('Поле %s содержит недопустимые символы' % field)
return value
def parse_create_user(raw):
data = _load_object(raw, ('username', 'display_name', 'password'))
username = data['username']
if not isinstance(username, str) or not USERNAME.fullmatch(username):
raise bad_request('username: 3-32 символа из набора a-z, 0-9 и _')
display_name = _string(data, 'display_name', MAX_NAME)
password = _string(data, 'password', MAX_PASSWORD, MIN_PASSWORD)
return username, display_name, password
def parse_create_chat(raw):
data = _load_object(raw, ('title', 'member_ids'))
title = _string(data, 'title', MAX_NAME)
raw_ids = data['member_ids']
if not isinstance(raw_ids, list) or not 1 <= len(raw_ids) <= MAX_MEMBERS:
raise bad_request('member_ids: список из 1-%d UUID' % MAX_MEMBERS)
member_ids = [parse_uuid(item) for item in raw_ids]
if None in member_ids:
raise bad_request('member_ids должен содержать только UUID')
if len(set(member_ids)) != len(member_ids):
raise bad_request('member_ids не должен содержать повторов')
return title, member_ids
def parse_create_message(raw):
return _string(_load_object(raw, ('text',)), 'text', MAX_TEXT)
def parse_idempotency_key(header):
"""Значение заголовка Idempotency-Key; без него или в неверном формате — 400."""
if header is None:
raise bad_request('Нужен заголовок Idempotency-Key')
if not IDEMPOTENCY_KEY.fullmatch(header):
raise bad_request('Idempotency-Key: от 1 до 128 символов из набора A-Z, a-z, 0-9 и ._:-')
return header
def request_fingerprint(text):
"""sha256 разобранного тела: порядок ключей и пробелы в JSON не влияют на сравнение повторов."""
canonical = json.dumps({'text': text}, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
def _credentials(header, scheme):
"""Значение после схемы авторизации (схема без учёта регистра) или None."""
if not header:
return None
name, _, value = header.strip().partition(' ')
if name.lower() != scheme:
return None
return value.strip()
def parse_basic(header):
"""(username, password) из Authorization: Basic base64(username:password) или None.
Пароль в UTF-8 и может содержать двоеточие: делим по первому. Всё, что не может быть
правильной парой логин/пароль, возвращает None — дальше это обычный ответ 401.
"""
value = _credentials(header, 'basic')
if not value:
return None
try:
decoded = base64.b64decode(value, validate=True).decode('utf-8')
except (binascii.Error, ValueError):
return None
username, separator, password = decoded.partition(':')
if not separator or not USERNAME.fullmatch(username):
return None
if not MIN_PASSWORD <= len(password) <= MAX_PASSWORD:
return None
return username, password
def parse_bearer(header):
"""Токен из Authorization: Bearer <token> или None."""
value = _credentials(header, 'bearer')
if not value or not BEARER_TOKEN.fullmatch(value):
return None
return value
def _single(query, name):
"""Значение параметра запроса; None, если параметра нет."""
values = query.get(name)
if values is None:
return None
if len(values) != 1:
raise bad_request('Параметр %s указан несколько раз' % name)
return values[0]
def parse_limit(query):
value = _single(query, 'limit')
if value is None:
return DEFAULT_LIMIT
if not LIMIT.fullmatch(value) or not 1 <= int(value) <= MAX_LIMIT:
raise bad_request('limit должен быть целым числом от 1 до %d' % MAX_LIMIT)
return int(value)
def encode_cursor(scope, key):
"""Непрозрачный для клиента cursor: область действия и ключ (created_at, id) последней записи."""
if key is None:
return None
raw = '%s|%d|%s' % (scope, key[0], key[1])
return base64.urlsafe_b64encode(raw.encode('ascii')).decode('ascii').rstrip('=')
def parse_cursor(query, scope):
"""Ключ (created_at в мкс, id), после которого продолжать; None без cursor.
scope привязывает cursor к ресурсу: cursor от другого чата — 400.
"""
value = _single(query, 'cursor')
if value is None:
return None
try:
padded = value + '=' * (-len(value) % 4)
raw = base64.b64decode(padded, altchars=b'-_', validate=True).decode('ascii')
cursor_scope, micros, entry_id = raw.split('|')
if cursor_scope != scope or not micros.isdigit() or parse_uuid(entry_id) != entry_id:
raise ValueError
# Ограничение длины защищает от чисел, которые не влезут в дату PostgreSQL.
if len(micros) > 17:
raise ValueError
return int(micros), entry_id
except ValueError:
raise bad_request('Некорректный cursor')
+144
View File
@@ -0,0 +1,144 @@
"""Небольшой HTTP-клиент для собственных тестов. Только стандартная библиотека, Python 3.9+.
Стенд должен быть уже запущен. Адрес берётся из переменной окружения BASE_URL.
По умолчанию 127.0.0.1, а не localhost: в Windows localhost сначала пробует IPv6
и каждый запрос к IPv4-порту занимает около двух секунд.
"""
import base64
import json
import os
import urllib.error
import urllib.request
import uuid
from datetime import datetime
from urllib.parse import quote
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8080').rstrip('/')
TIMEOUT = 10
USER_FIELDS = ('id', 'username', 'display_name', 'created_at')
# Значение по умолчанию для key: новый случайный Idempotency-Key у каждого POST сообщения.
AUTO = object()
class Response:
def __init__(self, status, headers, body):
self.status = status
self.headers = headers
self.body = body
self.json = json.loads(body) if body else None
def request(method, path, user=None, body=None, raw=None, headers=None, base_url=None, key=AUTO):
"""Один запрос. user — словарь с token (Bearer); body — объект для JSON; raw — готовые байты.
key — Idempotency-Key для POST сообщения: по умолчанию новый случайный, None — без заголовка.
"""
all_headers = {'Accept': 'application/json'}
if user is not None:
all_headers['Authorization'] = 'Bearer ' + user['token']
if key is AUTO:
key = uuid.uuid4().hex if method == 'POST' and path.endswith('/messages') else None
if key is not None:
all_headers['Idempotency-Key'] = key
if body is not None:
raw = json.dumps(body, ensure_ascii=False).encode('utf-8')
if raw is not None:
all_headers['Content-Type'] = 'application/json'
all_headers.update(headers or {})
req = urllib.request.Request((base_url or BASE_URL) + path, data=raw, headers=all_headers, method=method)
try:
response = urllib.request.urlopen(req, timeout=TIMEOUT)
except urllib.error.HTTPError as error:
response = error
with response:
result = Response(response.code, response.headers, response.read())
# Общие требования контракта ко всем ответам.
assert result.headers.get('X-Request-Id'), 'no X-Request-Id in response'
assert result.headers.get('X-Instance-Id'), 'no X-Instance-Id in response'
if result.status == 204:
assert not result.body, '204 must not have a body'
return result
assert result.headers.get_content_type() == 'application/json', 'response is not JSON'
if result.status >= 400:
error = result.json['error']
assert set(error) == {'code', 'message', 'request_id'}, 'unexpected error fields'
assert error['message'], 'empty error message'
assert error['request_id'] == result.headers['X-Request-Id'], 'request_id differs from header'
return result
def basic(username, password):
"""Значение заголовка Authorization: Basic base64(username:password) в UTF-8."""
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
def unique_username(prefix='t'):
return prefix + '_' + uuid.uuid4().hex[:16]
def new_password():
# Кириллица и двоеточие: проверяем UTF-8 и деление Basic по первому двоеточию.
return 'Пароль:' + uuid.uuid4().hex
def register(username=None, password=None, display_name='Тестовый пользователь'):
body = {'username': username or unique_username(), 'display_name': display_name, 'password': password or new_password()}
return request('POST', '/api/v1/users', body=body), body
def login(username, password, base_url=None):
return request('POST', '/api/v1/auth/sessions', headers={'Authorization': basic(username, password)},
base_url=base_url)
def new_user(display_name='Тестовый пользователь', base_url=None):
"""Зарегистрированный пользователь с действующим токеном: поля User + token + password."""
response, body = register(display_name=display_name)
assert response.status == 201, 'user was not created: %d' % response.status
session = login(body['username'], body['password'], base_url=base_url)
assert session.status == 201, 'login failed: %d' % session.status
return dict(response.json, token=session.json['token'], password=body['password'])
def public(user):
"""Только поля схемы User: так пользователь выглядит в ответах API."""
return {field: user[field] for field in USER_FIELDS}
def new_chat(owner, members, title='Тестовый чат'):
body = {'title': title, 'member_ids': [member['id'] for member in members]}
response = request('POST', '/api/v1/chats', user=owner, body=body)
assert response.status == 201, 'chat was not created: %d' % response.status
return response.json
def send(user, chat, text, key=AUTO):
return request('POST', '/api/v1/chats/%s/messages' % chat['id'], user=user, body={'text': text}, key=key)
def instance(response):
"""Какая реплика API ответила."""
return response.headers['X-Instance-Id']
def pages(path, user, limit):
"""Обходит все страницы списка и возвращает их как список списков."""
result = []
cursor = None
while True:
url = '%s?limit=%d' % (path, limit)
if cursor:
url += '&cursor=' + quote(cursor, safe='')
response = request('GET', url, user=user)
assert response.status == 200, 'page was not read: %d' % response.status
result.append(response.json['items'])
cursor = response.json['next_cursor']
if cursor is None:
return result
assert len(result) < 1000, 'pagination does not finish'
def order_key(item):
"""Порядок из контракта: (created_at, id) по возрастанию."""
created_at = datetime.fromisoformat(item['created_at'][:-1] + '+00:00')
return created_at, uuid.UUID(item['id']).int
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Проверка защиты от гонок: N клиентов одновременно отправляют сообщения в один чат.
python student-tests/race.py --output evidence/race.json
Каждый клиент — отдельный пользователь и отдельный поток. Все потоки стартуют
одновременно, затем история читается постранично и сравнивается с отправленным.
Код возврата 0 — в истории ровно столько уникальных сообщений, сколько отправлено.
"""
import argparse
import json
import sys
import threading
import time
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import api
def run_race(clients=10, per_client=10, page_size=7):
users = [api.new_user('Клиент %d' % n) for n in range(clients)]
chat = api.new_chat(users[0], users, title='Проверка гонок')
start = threading.Barrier(clients)
def client(index):
start.wait()
return [api.send(users[index], chat, 'race client=%d message=%d' % (index, n)) for n in range(per_client)]
started = time.monotonic()
with ThreadPoolExecutor(max_workers=clients) as pool:
responses = [response for batch in pool.map(client, range(clients)) for response in batch]
elapsed = time.monotonic() - started
accepted = [response.json for response in responses if response.status == 201]
pages = api.pages('/api/v1/chats/%s/messages' % chat['id'], users[-1], page_size)
history = [message for page in pages for message in page]
per_sender = Counter(message['sender_id'] for message in history)
expected = clients * per_client
summary = {
'base_url': api.BASE_URL,
'clients': clients,
'messages_per_client': per_client,
'sent': len(responses),
'accepted_201': len(accepted),
'history_total': len(history),
'history_unique_ids': len({message['id'] for message in history}),
'history_unique_texts': len({message['text'] for message in history}),
'history_matches_accepted': sorted(m['id'] for m in history) == sorted(m['id'] for m in accepted),
'senders_in_history': len(per_sender),
'min_messages_per_sender': min(per_sender.values(), default=0),
'max_messages_per_sender': max(per_sender.values(), default=0),
'ordered_by_created_at_and_id': history == sorted(history, key=api.order_key),
'pages_read': len(pages),
'page_size': page_size,
'send_elapsed_seconds': round(elapsed, 3),
}
summary['ok'] = (
summary['accepted_201'] == expected
and summary['history_total'] == expected
and summary['history_unique_ids'] == expected
and summary['history_unique_texts'] == expected
and summary['history_matches_accepted']
and summary['senders_in_history'] == clients
and summary['min_messages_per_sender'] == summary['max_messages_per_sender'] == per_client
and summary['ordered_by_created_at_and_id']
)
return summary
def main():
parser = argparse.ArgumentParser(description='Concurrent message race check; creates synthetic users and messages')
parser.add_argument('--clients', type=int, default=10)
parser.add_argument('--per-client', type=int, default=10)
parser.add_argument('--output', default=None, help='Optional JSON file for the summary')
args = parser.parse_args()
summary = run_race(args.clients, args.per_client)
text = json.dumps(summary, indent=2)
if args.output:
with open(args.output, 'w', encoding='utf-8') as file:
file.write(text + '\n')
print(text)
print('PASS' if summary['ok'] else 'FAIL')
return 0 if summary['ok'] else 1
if __name__ == '__main__':
sys.exit(main())
+87
View File
@@ -0,0 +1,87 @@
"""Доступ к чатам: аутентификация (кто ты) отдельно от доступа к конкретному чату (можно ли тебе сюда)."""
import unittest
import uuid
import api
class AuthenticationOrderTest(unittest.TestCase):
def test_authentication_is_checked_before_body_and_resource(self):
# Без токена сервер не сообщает ни об ошибке JSON, ни о наличии чата.
self.assertEqual(api.request('POST', '/api/v1/chats', raw=b'{broken').status, 401)
owner = api.new_user()
chat = api.new_chat(owner, [owner])
path = '/api/v1/chats/%s/messages' % chat['id']
self.assertEqual(api.request('GET', path).status, 401)
self.assertEqual(api.request('POST', path, raw=b'{broken').status, 401)
def test_registration_does_not_need_a_token(self):
response, _ = api.register()
self.assertEqual(response.status, 201)
class ForeignChatTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.alice, cls.bob, cls.eve = api.new_user('Алиса'), api.new_user('Боб'), api.new_user('Ева')
cls.chat = api.new_chat(cls.alice, [cls.alice, cls.bob])
cls.path = '/api/v1/chats/' + cls.chat['id']
assert api.send(cls.alice, cls.chat, 'секрет участников').status == 201
def assert_not_found(self, response):
self.assertEqual(response.status, 404)
self.assertEqual(response.json['error']['code'], 'not_found')
def test_outsider_cannot_get_chat(self):
self.assert_not_found(api.request('GET', self.path, user=self.eve))
def test_outsider_cannot_read_history(self):
self.assert_not_found(api.request('GET', self.path + '/messages', user=self.eve))
def test_outsider_cannot_write(self):
self.assert_not_found(api.send(self.eve, self.chat, 'чужое сообщение'))
# Даже с неверным телом посторонний видит 404, а не подсказку о валидации.
self.assert_not_found(api.request('POST', self.path + '/messages', user=self.eve, body={'text': ''}))
history = [m for page in api.pages(self.path + '/messages', self.alice, 100) for m in page]
self.assertNotIn('чужое сообщение', [m['text'] for m in history])
self.assertNotIn(self.eve['id'], [m['sender_id'] for m in history])
def test_foreign_chat_looks_like_missing_chat(self):
foreign = api.request('GET', self.path, user=self.eve)
missing = api.request('GET', '/api/v1/chats/' + str(uuid.uuid4()), user=self.eve)
self.assert_not_found(missing)
self.assertEqual(foreign.json['error']['code'], missing.json['error']['code'])
self.assertEqual(foreign.json['error']['message'], missing.json['error']['message'])
def test_chat_list_contains_only_own_chats(self):
def chat_ids(user):
return [chat['id'] for page in api.pages('/api/v1/chats', user, 100) for chat in page]
self.assertIn(self.chat['id'], chat_ids(self.alice))
self.assertIn(self.chat['id'], chat_ids(self.bob))
self.assertEqual(chat_ids(self.eve), [])
def test_every_member_can_read_and_write(self):
self.assertEqual(api.request('GET', self.path, user=self.bob).json, self.chat)
sent = api.send(self.bob, self.chat, 'ответ Боба')
self.assertEqual(sent.status, 201)
self.assertEqual(sent.json['sender_id'], self.bob['id'])
def test_x_user_id_does_not_open_a_foreign_chat(self):
# Ева подставляет id Алисы: доступ решает только владелец токена.
response = api.request('GET', self.path, user=self.eve, headers={'X-User-Id': self.alice['id']})
self.assert_not_found(response)
def test_invalid_chat_id_is_400(self):
for suffix in ('', '/messages'):
with self.subTest(suffix=suffix):
response = api.request('GET', '/api/v1/chats/not-a-uuid' + suffix, user=self.alice)
self.assertEqual(response.status, 400)
def test_unknown_route_is_404(self):
self.assert_not_found(api.request('GET', '/api/v1/unknown', user=self.alice))
self.assert_not_found(api.request('DELETE', self.path, user=self.alice))
if __name__ == '__main__':
unittest.main()
+39
View File
@@ -0,0 +1,39 @@
"""Балансировка: запросы одной сессии обслуживают разные реплики, состояние у них общее."""
import time
import unittest
import api
class BalancingTest(unittest.TestCase):
def test_one_session_is_served_by_several_replicas(self):
user = api.new_user('Балансировка')
responses = [api.request('GET', '/api/v1/users/me', user=user) for _ in range(20)]
self.assertEqual({response.status for response in responses}, {200})
# Сессия общая (Valkey), поэтому любая реплика узнаёт токен без повторного входа.
self.assertGreaterEqual(len({api.instance(response) for response in responses}), 2)
def test_message_written_on_one_replica_is_read_on_another(self):
alice, bob = api.new_user('Алиса'), api.new_user('Боб')
chat = api.new_chat(alice, [alice, bob])
sent = api.send(alice, chat, 'запись на одной реплике')
self.assertEqual(sent.status, 201)
writer = api.instance(sent)
path = '/api/v1/chats/%s/messages' % chat['id']
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
read = api.request('GET', path, user=bob)
if api.instance(read) != writer:
# Подтверждённое сообщение сразу видно через другую реплику.
self.assertEqual(read.json['items'], [sent.json])
return
self.fail('no response from another replica within 5 s')
def test_errors_also_carry_instance_id(self):
for method, path in (('GET', '/api/v1/users/me'), ('GET', '/api/v1/unknown'), ('GET', '/health/live')):
with self.subTest(path=path):
self.assertTrue(api.instance(api.request(method, path)))
if __name__ == '__main__':
unittest.main()
+62
View File
@@ -0,0 +1,62 @@
"""Параллельные запросы не должны терять, дублировать или портить данные."""
import threading
import unittest
from concurrent.futures import ThreadPoolExecutor
import api
from race import run_race
class ConcurrencyTest(unittest.TestCase):
def test_100_messages_from_10_clients(self):
summary = run_race(clients=10, per_client=10)
self.assertEqual(summary['accepted_201'], 100)
self.assertEqual(summary['history_total'], 100)
self.assertEqual(summary['history_unique_ids'], 100)
self.assertEqual(summary['history_unique_texts'], 100)
self.assertTrue(summary['history_matches_accepted'])
self.assertEqual(summary['senders_in_history'], 10)
self.assertEqual((summary['min_messages_per_sender'], summary['max_messages_per_sender']), (10, 10))
self.assertTrue(summary['ordered_by_created_at_and_id'])
def test_same_username_registered_in_parallel_wins_once(self):
# Уникальность username держит индекс PostgreSQL: из одновременных INSERT проходит один,
# остальные получают нарушение уникальности, и API отвечает 409.
attempts = 20
username = api.unique_username()
passwords = ['Гонка-пароль-%02d' % n for n in range(attempts)]
start = threading.Barrier(attempts)
def register(index):
start.wait()
body = {'username': username, 'display_name': 'Гонка %d' % index, 'password': passwords[index]}
return api.request('POST', '/api/v1/users', body=body)
with ThreadPoolExecutor(max_workers=attempts) as pool:
responses = list(pool.map(register, range(attempts)))
statuses = sorted(response.status for response in responses)
self.assertEqual(statuses, [201] + [409] * (attempts - 1))
# Победитель один, и войти можно только с его паролем.
winner = next(index for index, response in enumerate(responses) if response.status == 201)
logins = [api.login(username, password).status for password in passwords]
self.assertEqual(logins, [201 if index == winner else 401 for index in range(attempts)])
def test_chats_created_in_parallel_are_all_listed(self):
user = api.new_user()
count = 30
start = threading.Barrier(count)
def create(index):
start.wait()
return api.new_chat(user, [user], title='Параллельный чат %d' % index)
with ThreadPoolExecutor(max_workers=count) as pool:
created = list(pool.map(create, range(count)))
listed = [chat for page in api.pages('/api/v1/chats', user, 7) for chat in page]
self.assertEqual(len(listed), count)
self.assertEqual({chat['id'] for chat in listed}, {chat['id'] for chat in created})
self.assertEqual(listed, sorted(listed, key=api.order_key))
if __name__ == '__main__':
unittest.main()
+106
View File
@@ -0,0 +1,106 @@
"""Идемпотентность отправки сообщения: Idempotency-Key общий для всех реплик."""
import threading
import unittest
import uuid
from concurrent.futures import ThreadPoolExecutor
import api
class IdempotencyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.alice, cls.bob = api.new_user('Алиса'), api.new_user('Боб')
cls.chat = api.new_chat(cls.alice, [cls.alice, cls.bob])
cls.path = '/api/v1/chats/%s/messages' % cls.chat['id']
def history(self):
return [m for page in api.pages(self.path, self.alice, 100) for m in page]
def test_replay_returns_the_same_message(self):
key = uuid.uuid4().hex
first = api.send(self.alice, self.chat, 'повтор ' + key, key=key)
second = api.send(self.alice, self.chat, 'повтор ' + key, key=key)
self.assertEqual((first.status, second.status), (201, 201))
self.assertEqual(second.json, first.json)
self.assertEqual([m['text'] for m in self.history()].count('повтор ' + key), 1)
def test_same_key_with_another_body_is_409(self):
key = uuid.uuid4().hex
self.assertEqual(api.send(self.alice, self.chat, 'первое тело', key=key).status, 201)
response = api.send(self.alice, self.chat, 'другое тело', key=key)
self.assertEqual(response.status, 409)
self.assertEqual(response.json['error']['code'], 'conflict')
self.assertNotIn('другое тело', [m['text'] for m in self.history()])
def test_json_formatting_does_not_matter(self):
# Пробелы и запись Unicode в JSON не меняют смысл тела: это тот же повтор.
key = uuid.uuid4().hex
first = api.request('POST', self.path, user=self.alice, raw='{"text":"Привет"}'.encode(), key=key)
second = api.request('POST', self.path, user=self.alice, raw=b'{ "text" : "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442" }', key=key)
self.assertEqual((first.status, second.status), (201, 201))
self.assertEqual(second.json, first.json)
def test_missing_key_is_400(self):
response = api.send(self.alice, self.chat, 'без ключа', key=None)
self.assertEqual(response.status, 400)
self.assertNotIn('без ключа', [m['text'] for m in self.history()])
def test_invalid_keys_are_400(self):
# Кириллица уходит в заголовок байтами UTF-8, как её отправил бы обычный клиент.
cyrillic = 'кириллица'.encode('utf-8').decode('latin-1')
for key in ('', 'a' * 129, cyrillic, 'with space', 'semi;colon', 'slash/key'):
with self.subTest(key=key):
self.assertEqual(api.send(self.alice, self.chat, 'ключ', key=key).status, 400)
def test_key_format_limits_are_accepted(self):
# Свой чат на каждый запуск: область ключа включает чат, поэтому ключи не пересекаются с прошлыми.
chat = api.new_chat(self.alice, [self.alice], title='Форматы ключей')
for key in ('a' * 128, 'A.b_c:d-1', '0'):
with self.subTest(key=key[:20]):
self.assertEqual(api.send(self.alice, chat, 'формат ' + key, key=key).status, 201)
def test_key_scope_is_user_and_chat(self):
key = uuid.uuid4().hex
other_chat = api.new_chat(self.alice, [self.alice], title='Другой чат')
first = api.send(self.alice, self.chat, 'одинаковый ключ', key=key)
in_other_chat = api.send(self.alice, other_chat, 'одинаковый ключ', key=key)
by_other_user = api.send(self.bob, self.chat, 'одинаковый ключ', key=key)
self.assertEqual({first.status, in_other_chat.status, by_other_user.status}, {201})
self.assertEqual(len({first.json['id'], in_other_chat.json['id'], by_other_user.json['id']}), 3)
def test_failed_validation_is_not_remembered(self):
# Ответ 400 не фиксируется: тот же ключ можно использовать с исправленным телом.
key = uuid.uuid4().hex
self.assertEqual(api.send(self.alice, self.chat, ' ', key=key).status, 400)
self.assertEqual(api.send(self.alice, self.chat, 'исправлено', key=key).status, 201)
def test_replay_checks_the_session_again(self):
user = api.new_user('Выход')
chat = api.new_chat(user, [user])
key = uuid.uuid4().hex
self.assertEqual(api.send(user, chat, 'до выхода', key=key).status, 201)
api.request('DELETE', '/api/v1/auth/sessions/current', user=user)
self.assertEqual(api.send(user, chat, 'до выхода', key=key).status, 401)
def test_parallel_requests_with_one_key_create_one_message(self):
# Одновременные повторы расходятся по разным репликам и всё равно создают одно сообщение.
key = uuid.uuid4().hex
text = 'параллельно ' + key
attempts = 20
start = threading.Barrier(attempts)
def post(_):
start.wait()
return api.send(self.alice, self.chat, text, key=key)
with ThreadPoolExecutor(max_workers=attempts) as pool:
responses = list(pool.map(post, range(attempts)))
self.assertEqual({response.status for response in responses}, {201})
self.assertEqual(len({response.json['id'] for response in responses}), 1)
self.assertGreaterEqual(len({api.instance(response) for response in responses}), 2)
self.assertEqual([m['text'] for m in self.history()].count(text), 1)
if __name__ == '__main__':
unittest.main()
+127
View File
@@ -0,0 +1,127 @@
"""Keyset-пагинация истории сообщений и списка чатов."""
import unittest
from urllib.parse import quote
import api
class MessagePaginationTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.user = api.new_user()
cls.chat = api.new_chat(cls.user, [cls.user])
cls.path = '/api/v1/chats/%s/messages' % cls.chat['id']
cls.sent = [api.send(cls.user, cls.chat, 'сообщение %d' % n).json for n in range(25)]
def get(self, query):
return api.request('GET', self.path + query, user=self.user)
def test_walk_over_several_pages(self):
pages = api.pages(self.path, self.user, 10)
self.assertEqual([len(page) for page in pages], [10, 10, 5])
history = [message for page in pages for message in page]
# Ничего не потеряно, не повторено и не переставлено.
self.assertEqual(history, self.sent)
self.assertEqual(history, sorted(history, key=api.order_key))
self.assertEqual(len({message['id'] for message in history}), 25)
def test_one_message_per_page(self):
pages = api.pages(self.path, self.user, 1)
self.assertEqual(len(pages), 25)
self.assertEqual([page[0] for page in pages], self.sent)
def test_last_full_page_has_no_cursor(self):
# 25 сообщений по 5: на пятой странице следующей записи нет, cursor сразу null.
pages = api.pages(self.path, self.user, 5)
self.assertEqual([len(page) for page in pages], [5, 5, 5, 5, 5])
def test_default_and_maximum_limit(self):
self.assertEqual(len(self.get('').json['items']), 25)
everything = self.get('?limit=100').json
self.assertEqual(everything['items'], self.sent)
self.assertIsNone(everything['next_cursor'])
def test_limit_can_change_between_pages(self):
first = self.get('?limit=3').json
second = self.get('?limit=20&cursor=' + quote(first['next_cursor'], safe='')).json
self.assertEqual(first['items'] + second['items'], self.sent[:23])
self.assertIsNotNone(second['next_cursor'])
def test_invalid_limit_is_400(self):
for limit in ('0', '101', '-1', '1.5', 'abc', '', '1e2', '٣'):
with self.subTest(limit=limit):
response = self.get('?limit=' + quote(limit))
self.assertEqual(response.status, 400)
self.assertEqual(response.json['error']['code'], 'invalid_request')
def test_invalid_cursor_is_400(self):
for cursor in ('garbage', '', '!!!', 'AAAA', quote('курсор')):
with self.subTest(cursor=cursor):
self.assertEqual(self.get('?cursor=' + cursor).status, 400)
def test_cursor_from_another_chat_is_400(self):
other = api.new_chat(self.user, [self.user], title='Другой чат')
for n in range(3):
api.send(self.user, other, 'в другом чате %d' % n)
other_cursor = api.request('GET', '/api/v1/chats/%s/messages?limit=1' % other['id'], user=self.user).json['next_cursor']
self.assertIsNotNone(other_cursor)
self.assertEqual(self.get('?cursor=' + quote(other_cursor, safe='')).status, 400)
# Cursor списка чатов тоже не подходит к истории сообщений.
chats_cursor = api.request('GET', '/api/v1/chats?limit=1', user=self.user).json['next_cursor']
self.assertEqual(self.get('?cursor=' + quote(chats_cursor, safe='')).status, 400)
class DefaultLimitTest(unittest.TestCase):
def test_default_limit_is_50(self):
user = api.new_user()
chat = api.new_chat(user, [user])
path = '/api/v1/chats/%s/messages' % chat['id']
for n in range(55):
api.send(user, chat, 'сообщение %d' % n)
first = api.request('GET', path, user=user).json
self.assertEqual(len(first['items']), 50)
rest = api.request('GET', path + '?cursor=' + quote(first['next_cursor'], safe=''), user=user).json
self.assertEqual(len(rest['items']), 5)
self.assertIsNone(rest['next_cursor'])
class GrowingHistoryTest(unittest.TestCase):
def test_empty_history(self):
user = api.new_user()
chat = api.new_chat(user, [user])
page = api.request('GET', '/api/v1/chats/%s/messages' % chat['id'], user=user).json
self.assertEqual(page, {'items': [], 'next_cursor': None})
def test_messages_sent_during_walk_are_not_lost(self):
alice, bob = api.new_user(), api.new_user()
chat = api.new_chat(alice, [alice, bob])
path = '/api/v1/chats/%s/messages' % chat['id']
before = [api.send(alice, chat, 'до %d' % n).json for n in range(4)]
first = api.request('GET', path + '?limit=2', user=bob).json
# Пока Боб читает, Алиса дописывает; cursor Боба продолжает работать у любого участника.
after = [api.send(alice, chat, 'после %d' % n).json for n in range(3)]
rest = api.request('GET', path + '?limit=100&cursor=' + quote(first['next_cursor'], safe=''), user=alice).json
self.assertEqual(first['items'] + rest['items'], before + after)
class ChatListPaginationTest(unittest.TestCase):
def test_chats_are_paged_in_creation_order(self):
user = api.new_user()
created = [api.new_chat(user, [user], title='Чат %d' % n) for n in range(5)]
pages = api.pages('/api/v1/chats', user, 2)
self.assertEqual([len(page) for page in pages], [2, 2, 1])
chats = [chat for page in pages for chat in page]
self.assertEqual(chats, created)
self.assertEqual(chats, sorted(chats, key=api.order_key))
def test_cursor_of_another_user_is_400(self):
alice, bob = api.new_user(), api.new_user()
for n in range(2):
api.new_chat(alice, [alice, bob], title='Общий %d' % n)
alice_cursor = api.request('GET', '/api/v1/chats?limit=1', user=alice).json['next_cursor']
response = api.request('GET', '/api/v1/chats?limit=1&cursor=' + quote(alice_cursor, safe=''), user=bob)
self.assertEqual(response.status, 400)
if __name__ == '__main__':
unittest.main()
+160
View File
@@ -0,0 +1,160 @@
"""Вход по Basic, Bearer-сессии, выход. X-User-Id из lab1 больше не даёт доступа."""
import base64
import unittest
import uuid
from datetime import datetime, timedelta, timezone
import api
ME = '/api/v1/users/me'
SESSIONS = '/api/v1/auth/sessions'
def b64(raw):
return base64.b64encode(raw).decode('ascii')
class LoginTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
response, cls.registration = api.register(display_name='Вход')
assert response.status == 201
cls.user = response.json
def assert_login_rejected(self, response):
self.assertEqual(response.status, 401)
self.assertEqual(response.json['error']['code'], 'unauthorized')
self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="messenger", charset="UTF-8"')
return response.json['error']['message']
def test_successful_login(self):
response = api.login(self.registration['username'], self.registration['password'])
self.assertEqual(response.status, 201)
session = response.json
self.assertEqual(set(session), {'token', 'token_type', 'expires_at', 'user'})
self.assertEqual(session['token_type'], 'Bearer')
self.assertEqual(session['user'], self.user)
# Непрозрачный случайный токен: 256 бит в base64url — 43 символа; это не id и не username.
self.assertGreaterEqual(len(session['token']), 43)
self.assertNotIn(self.user['id'], session['token'])
self.assertNotIn(self.user['username'], session['token'])
expires_at = datetime.fromisoformat(session['expires_at'][:-1] + '+00:00')
self.assertGreater(expires_at, datetime.now(timezone.utc) + timedelta(seconds=60))
me = api.request('GET', ME, headers={'Authorization': 'Bearer ' + session['token']})
self.assertEqual(me.json, self.user)
def test_each_login_gives_a_new_token(self):
first = api.login(self.registration['username'], self.registration['password']).json['token']
second = api.login(self.registration['username'], self.registration['password']).json['token']
self.assertNotEqual(first, second)
for token in (first, second):
self.assertEqual(api.request('GET', ME, headers={'Authorization': 'Bearer ' + token}).status, 200)
def test_registration_never_returns_password(self):
response, _ = api.register()
self.assertEqual(set(response.json), {'id', 'username', 'display_name', 'created_at'})
def test_wrong_password(self):
self.assert_login_rejected(api.login(self.registration['username'], self.registration['password'] + 'x'))
def test_unknown_user_gets_the_same_answer(self):
wrong_password = self.assert_login_rejected(api.login(self.registration['username'], 'Wrong-password-123'))
unknown_user = self.assert_login_rejected(api.login(api.unique_username(), 'Wrong-password-123'))
self.assertEqual(wrong_password, unknown_user)
def test_malformed_basic_header(self):
for value in (
'Basic',
'Basic !!!not-base64!!!',
'Basic ' + b64(b'no-colon-here'),
'Basic ' + b64(b'\xff\xfe:invalid-utf8-password'),
'Basic ' + b64(b'Upper_Case:Valid-password-123'),
'Basic ' + b64(b'short:pw'),
'Digest abc',
'Bearer ' + uuid.uuid4().hex,
):
with self.subTest(value=value):
response = api.request('POST', SESSIONS, headers={'Authorization': value})
self.assert_login_rejected(response)
self.assert_login_rejected(api.request('POST', SESSIONS))
def test_password_with_colons_and_unicode(self):
password = 'Пароль:с:двоеточиями 👋'
response, body = api.register(password=password)
self.assertEqual(response.status, 201)
self.assertEqual(api.login(body['username'], password).status, 201)
self.assert_login_rejected(api.login(body['username'], 'Пароль:с:двоеточиями'))
def test_credentials_in_json_body_are_not_accepted(self):
body = {'username': self.registration['username'], 'password': self.registration['password']}
response = api.request('POST', SESSIONS, body=body)
self.assertIn(response.status, (400, 401))
self.assertNotIn('token', response.json)
class BearerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.alice = api.new_user('Алиса')
cls.bob = api.new_user('Боб')
def assert_bearer_rejected(self, response):
self.assertEqual(response.status, 401)
self.assertEqual(response.json['error']['code'], 'unauthorized')
self.assertEqual(response.headers['WWW-Authenticate'], 'Bearer realm="messenger"')
def test_protected_endpoints_need_a_token(self):
for method, path in (('GET', ME), ('GET', '/api/v1/chats'), ('POST', '/api/v1/chats'),
('GET', '/api/v1/chats/%s/messages' % uuid.uuid4()), ('DELETE', SESSIONS + '/current')):
with self.subTest(method=method, path=path):
self.assert_bearer_rejected(api.request(method, path))
def test_unknown_or_malformed_token(self):
for value in ('Bearer ' + uuid.uuid4().hex * 2, 'Bearer', 'Bearer a b', 'Bearer ' + 'x' * 600,
'Bearer ' + self.alice['id'], 'Token ' + self.alice['token']):
with self.subTest(value=value[:40]):
self.assert_bearer_rejected(api.request('GET', ME, headers={'Authorization': value}))
def test_basic_is_rejected_on_business_endpoints(self):
value = api.basic(self.alice['username'], self.alice['password'])
self.assert_bearer_rejected(api.request('GET', ME, headers={'Authorization': value}))
def test_x_user_id_is_ignored(self):
self.assert_bearer_rejected(api.request('GET', ME, headers={'X-User-Id': self.alice['id']}))
# Заголовок X-User-Id не меняет владельца сессии.
me = api.request('GET', ME, user=self.alice, headers={'X-User-Id': self.bob['id']})
self.assertEqual(me.json, api.public(self.alice))
def test_token_selects_the_user(self):
self.assertEqual(api.request('GET', ME, user=self.alice).json, api.public(self.alice))
self.assertEqual(api.request('GET', ME, user=self.bob).json, api.public(self.bob))
def test_scheme_name_is_case_insensitive(self):
# RFC 7235: имя схемы авторизации не зависит от регистра.
response = api.request('GET', ME, headers={'Authorization': 'bearer ' + self.alice['token']})
self.assertEqual(response.status, 200)
class LogoutTest(unittest.TestCase):
def test_logout_revokes_only_the_current_token(self):
user = api.new_user('Выход')
other = api.login(user['username'], user['password']).json['token']
response = api.request('DELETE', SESSIONS + '/current', user=user)
self.assertEqual(response.status, 204)
self.assertEqual(response.body, b'')
# Отозванный токен больше не работает, повторный выход — тоже 401.
self.assertEqual(api.request('GET', ME, user=user).status, 401)
self.assertEqual(api.request('DELETE', SESSIONS + '/current', user=user).status, 401)
# Другая сессия того же пользователя продолжает работать.
self.assertEqual(api.request('GET', ME, headers={'Authorization': 'Bearer ' + other}).status, 200)
def test_login_again_after_logout(self):
user = api.new_user('Снова')
api.request('DELETE', SESSIONS + '/current', user=user)
again = api.login(user['username'], user['password'])
self.assertEqual(again.status, 201)
self.assertNotEqual(again.json['token'], user['token'])
if __name__ == '__main__':
unittest.main()
+219
View File
@@ -0,0 +1,219 @@
"""Валидация входных данных: неверный JSON, пустое сообщение, дубликат username, пароль, Unicode."""
import json
import unittest
import uuid
import api
USERS = '/api/v1/users'
PASSWORD = 'Valid-password-123'
def registration(**fields):
"""Корректное тело регистрации; fields заменяют или добавляют поля."""
body = {'username': api.unique_username(), 'display_name': 'Имя', 'password': PASSWORD}
body.update(fields)
return body
class InvalidJsonTest(unittest.TestCase):
def assert_invalid(self, response):
self.assertEqual(response.status, 400)
self.assertEqual(response.json['error']['code'], 'invalid_request')
def test_malformed_json_on_register(self):
self.assert_invalid(api.request('POST', USERS, raw=b'{"username": "broken", '))
def test_malformed_json_on_message(self):
user = api.new_user()
chat = api.new_chat(user, [user])
path = '/api/v1/chats/%s/messages' % chat['id']
for raw in (b'not json', b'{"text": "no closing quote}', b'', b'{"text": }'):
with self.subTest(raw=raw):
self.assert_invalid(api.request('POST', path, user=user, raw=raw))
# Неудачные запросы ничего не записали в историю.
self.assertEqual(api.pages(path, user, 100), [[]])
def test_json_that_is_not_an_object(self):
for raw in (b'[]', b'"text"', b'42', b'null'):
with self.subTest(raw=raw):
self.assert_invalid(api.request('POST', USERS, raw=raw))
def test_invalid_utf8(self):
raw = json.dumps(registration(display_name='PLACEHOLDER')).encode().replace(b'PLACEHOLDER', b'\xff\xfe')
self.assert_invalid(api.request('POST', USERS, raw=raw))
def test_lone_surrogate_is_rejected_not_crashed(self):
# Всё остальное в теле корректно: ошибка именно в одиночном суррогате.
raw = json.dumps(registration(display_name='PLACEHOLDER')).encode().replace(b'PLACEHOLDER', b'\\ud800')
self.assert_invalid(api.request('POST', USERS, raw=raw))
def test_nul_character_is_rejected_not_crashed(self):
# PostgreSQL не хранит символ NUL в text: без проверки это был бы 500.
self.assert_invalid(api.request('POST', USERS, body=registration(display_name='a\x00b')))
def test_extra_fields(self):
self.assert_invalid(api.request('POST', USERS, body=registration(is_admin=True)))
def test_wrong_types(self):
for fields in ({'username': 12345}, {'display_name': ['Имя']}, {'display_name': None}, {'password': 123456789012345}):
with self.subTest(fields=fields):
self.assert_invalid(api.request('POST', USERS, body=registration(**fields)))
def test_wrong_content_type(self):
raw = json.dumps(registration()).encode()
self.assert_invalid(api.request('POST', USERS, raw=raw, headers={'Content-Type': 'text/plain'}))
class UserValidationTest(unittest.TestCase):
def test_duplicate_username_is_409(self):
body = registration(display_name='Первый')
first = api.request('POST', USERS, body=body)
self.assertEqual(first.status, 201)
# Совпадает только username: другие имя и пароль не помогают.
second = api.request('POST', USERS, body=dict(body, display_name='Второй', password='Another-password-456'))
self.assertEqual(second.status, 409)
self.assertEqual(second.json['error']['code'], 'conflict')
# Первый пользователь не изменился: входит со своим паролем и видит своё имя.
session = api.login(body['username'], body['password'])
self.assertEqual(session.json['user'], first.json)
self.assertEqual(api.login(body['username'], 'Another-password-456').status, 401)
def test_bad_usernames(self):
for username in ('ab', 'a' * 33, 'Alice', 'with space', 'дмитрий', 'dash-name', '', 'name\n', 'colon:name'):
with self.subTest(username=username):
self.assertEqual(api.request('POST', USERS, body=registration(username=username)).status, 400)
def test_username_length_limits_are_accepted(self):
for length in (3, 32):
with self.subTest(length=length):
response = api.request('POST', USERS, body=registration(username=uuid.uuid4().hex[:length]))
# Трёхсимвольное имя могло остаться от прошлого запуска: 409 тоже значит «имя допустимо».
self.assertIn(response.status, (201, 409))
def test_bad_display_names(self):
for display_name in ('', ' ', '\t\n', 'я' * 101):
with self.subTest(display_name=display_name):
self.assertEqual(api.request('POST', USERS, body=registration(display_name=display_name)).status, 400)
def test_bad_passwords(self):
for password in ('a' * 11, 'я' * 11, 'a' * 129, ' ' * 12, '\t' * 20, 'pass\x00word-123'):
with self.subTest(password=password[:20]):
self.assertEqual(api.request('POST', USERS, body=registration(password=password)).status, 400)
def test_password_length_limits_are_accepted(self):
# Длина считается в code points: 12 кириллических букв — это 24 байта UTF-8.
for password in ('a' * 12, 'я' * 12, '👋' * 128):
with self.subTest(length=len(password)):
body = registration(password=password)
self.assertEqual(api.request('POST', USERS, body=body).status, 201)
self.assertEqual(api.login(body['username'], password).status, 201)
def test_missing_fields(self):
for field in ('username', 'display_name', 'password'):
with self.subTest(field=field):
body = registration()
del body[field]
self.assertEqual(api.request('POST', USERS, body=body).status, 400)
def test_unicode_display_name_is_kept(self):
# Длина считается в code points: 100 эмодзи — это 400 байт, но имя допустимо.
for display_name in ('Дмитрий 👋', '李雷', '👋' * 100):
with self.subTest(display_name=display_name):
response = api.request('POST', USERS, body=registration(display_name=display_name))
self.assertEqual(response.status, 201)
self.assertEqual(response.json['display_name'], display_name)
class MessageValidationTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.user = api.new_user()
cls.chat = api.new_chat(cls.user, [cls.user])
cls.path = '/api/v1/chats/%s/messages' % cls.chat['id']
def test_empty_message_is_400(self):
for text in ('', ' ', '\n\t \r\n', '  '):
with self.subTest(text=text):
response = api.send(self.user, self.chat, text)
self.assertEqual(response.status, 400)
self.assertEqual(response.json['error']['code'], 'invalid_request')
def test_missing_or_wrong_text(self):
for body in ({}, {'text': None}, {'text': 123}, {'text': ['a']}, {'message': 'a'}):
with self.subTest(body=body):
self.assertEqual(api.request('POST', self.path, user=self.user, body=body).status, 400)
def test_sender_id_in_body_is_rejected(self):
other = api.new_user()
body = {'text': 'подмена отправителя', 'sender_id': other['id']}
self.assertEqual(api.request('POST', self.path, user=self.user, body=body).status, 400)
def test_nul_in_text_is_400(self):
self.assertEqual(api.send(self.user, self.chat, 'до\x00после').status, 400)
def test_text_length_limit(self):
self.assertEqual(api.send(self.user, self.chat, 'я' * 4000).status, 201)
self.assertEqual(api.send(self.user, self.chat, '👋' * 4000).status, 201)
self.assertEqual(api.send(self.user, self.chat, 'я' * 4001).status, 400)
def test_unicode_text_is_kept(self):
text = 'Привет, мир 👋 — 你好\nвторая строка'
response = api.send(self.user, self.chat, text)
self.assertEqual(response.status, 201)
self.assertEqual(response.json['text'], text)
self.assertEqual(response.json['sender_id'], self.user['id'])
self.assertEqual(response.json['chat_id'], self.chat['id'])
def test_oversized_body_is_413(self):
response = api.request('POST', self.path, user=self.user, body={'text': 'a' * 70000})
self.assertEqual(response.status, 413)
self.assertEqual(response.json['error']['code'], 'payload_too_large')
class ChatValidationTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.alice = api.new_user()
cls.bob = api.new_user()
def create(self, title, member_ids):
return api.request('POST', '/api/v1/chats', user=self.alice, body={'title': title, 'member_ids': member_ids})
def test_caller_must_be_a_member(self):
self.assertEqual(self.create('Без меня', [self.bob['id']]).status, 400)
def test_duplicate_members(self):
self.assertEqual(self.create('Дубликат', [self.alice['id'], self.bob['id'], self.bob['id']]).status, 400)
# Тот же UUID в другом регистре — тоже дубликат.
self.assertEqual(self.create('Дубликат', [self.alice['id'], self.alice['id'].upper()]).status, 400)
def test_unknown_member_rolls_back_the_whole_chat(self):
# Чат вставляется первым, участник — вторым; ошибка на участнике откатывает и сам чат.
title = 'Откат ' + uuid.uuid4().hex[:8]
response = self.create(title, [self.alice['id'], str(uuid.uuid4())])
self.assertEqual(response.status, 400)
chats = [chat for page in api.pages('/api/v1/chats', self.alice, 100) for chat in page]
self.assertNotIn(title, [chat['title'] for chat in chats])
def test_bad_member_ids(self):
for member_ids in ([], 'not a list', [123], ['not-a-uuid'], None):
with self.subTest(member_ids=member_ids):
self.assertEqual(self.create('Чат', member_ids).status, 400)
def test_bad_titles(self):
for title in ('', ' ', 'я' * 101, 5, 'a\x00b'):
with self.subTest(title=title):
self.assertEqual(self.create(title, [self.alice['id']]).status, 400)
def test_valid_chat_keeps_member_order(self):
response = self.create('Проект по ВНП', [self.bob['id'], self.alice['id']])
self.assertEqual(response.status, 201)
self.assertEqual(response.json['title'], 'Проект по ВНП')
self.assertEqual(response.json['member_ids'], [self.bob['id'], self.alice['id']])
again = api.request('GET', '/api/v1/chats/' + response.json['id'], user=self.bob)
self.assertEqual(again.json, response.json)
if __name__ == '__main__':
unittest.main()