Author SHA1 Message Date
IlyaandClaude Opus 5.5 55730e14fd Заполнить автора и ссылку на PR в отчёте
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:51:18 +03:00
IlyaandClaude Opus 5.5 b3d3088408 Показывать сводку RPS/ошибок в make chaos
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:50:13 +03:00
Ilya 6f4f74d691 выполнение ЛР3 на 4 2026-10-21 12:20:11 +03:00
37 changed files with 2856 additions and 17 deletions
+363
View File
@@ -0,0 +1,363 @@
# Демонстрация лабораторной 3 на защите
Сценарий повторяет раздел «Сценарий защиты» из README: стенд поднимается с нуля на пустом volume, затем показываются балансировка одной сессии по репликам, идемпотентность, остановка каждой реплики, рестарт всего стенда и эксперименты уровня 4.
**Важно:** выполняйте команды по порядку **в одном окне терминала**. Переменные `B`, `TA`, `TB`, `ALICE`, `BOB`, `CHAT`, `KEY` и функции `j`, `pg`, `ids` живут только в этом окне.
---
## 0. Подготовка: чистый clone
Если запущен рабочий стенд, останавливаем его. Volume сохраняется, порт освобождается:
```bash
(cd ~/Desktop/вуз/ВНП/lab3/mtusi2026lab3 && docker compose stop)
```
Скачиваем решение в новую папку:
```bash
git clone -b solution/bvt2304-koshelev ssh://git@gitea.privcloud.tech:2222/Iicon18/mtusi2026lab3.git ~/Desktop/lab3-demo
```
```bash
cd ~/Desktop/lab3-demo
```
Отдельное имя compose-проекта даёт отдельные контейнеры и **новый пустой volume**:
```bash
export COMPOSE_PROJECT_NAME=lab3-demo
```
```bash
cp .env.example .env
```
Если порт 8080 занят (у меня его держит посторонний контейнер `romashka-frontend`), меняем `APP_PORT` в `.env`, например на 8088. Следующая команда подхватит значение:
```bash
B=http://127.0.0.1:$(sed -n 's/^APP_PORT=//p' .env); echo "$B"
```
Вспомогательные функции: достать поле из JSON, выполнить SQL, показать заголовок `X-Instance-Id`.
```bash
j() { python3 -c 'import sys,json;print(json.load(sys.stdin)[sys.argv[1]])' "$1"; }
pg() { docker compose exec -T postgres psql -U messenger -d messenger -c "$1"; }
ids() { for c in $(docker compose ps -q api); do printf '%s -> %s\n' "$(docker inspect -f '{{.Name}}' $c)" "$(docker exec $c cat /tmp/instance-id)"; done; }
```
> **Сказать:** «Это свежий clone моей ветки в отдельный compose-проект, база будет пустой. `.env` и секреты не хранятся в Git, создаю их локально».
---
## 1. Секреты
```bash
make secrets
```
```bash
git check-ignore -v secrets/database_url .env
```
> **Сказать:** «Как в lab2: `scripts/init-secrets.sh` генерирует пароли PostgreSQL и Valkey в `secrets/` (в `.gitignore`). В контейнеры они приходят как compose secrets файлами `/run/secrets/...`. Балансировщику секреты не выдаются вообще — ему они не нужны».
---
## 2. Топология и запуск
```bash
cat compose.yaml
```
> **Сказать:**
> - «Пять сервисов: `lb` (HAProxy) — единственная публичная точка входа; `api` — приложение, `deploy.replicas: 2`; `migrate` — одноразовые миграции; `postgres` — источник истины; `valkey` — общий кэш сессий».
> - «У `api` нет `ports` и нет `container_name`: снаружи до реплик не достучаться в обход LB, и сервис можно масштабировать (`API_REPLICAS=4`)».
> - «Две сети: `edge` (lb ↔ api) и `data` (api ↔ postgres/valkey) с `internal: true`. БД и кэш недоступны ни с хоста, ни из балансировщика».
> - «У каждого контейнера лимиты CPU/RAM в `deploy.resources.limits`. Версии образов закреплены, `latest` нигде нет».
> - «`api` стартует только после `migrate` с кодом 0 — миграции выполняет один процесс, а не гонка реплик».
```bash
make up
```
```bash
docker compose ps --all --format 'table {{.Name}}\t{{.Status}}\t{{.Ports}}'
```
```bash
docker compose logs migrate --no-log-prefix | tail -2
```
> **Сказать:** «Опубликован только порт `lb`. Обе реплики `healthy`. `migrate` применил `0001_init` и `0002_idempotency` и завершился».
---
## 3. Конфигурация балансировщика
```bash
cat infra/haproxy/haproxy.cfg
```
> **Сказать:**
> - «`server-template api 8 api:8080` + `resolvers docker`: адреса реплик HAProxy берёт из встроенного DNS Docker (`127.0.0.11`). Поэтому масштабирование и перезапуск реплики с новым IP не требуют перезагрузки LB».
> - «Активная проверка готовности: `GET /health/ready` каждую секунду (`inter 1s`), реплика выводится после 2 неудач (`fall 2`), возвращается после 2 успехов (`rise 2`). Максимальное время обнаружения ≈ 3 с».
> - «`balance roundrobin`, никакой привязки клиента (sticky) нет».
> - «`timeout connect 1s`, `retries 3`, `option redispatch 1`, `retry-on conn-failure empty-response`: если до реплики не удалось достучаться, запрос повторяется на **другой** реплике. Для POST это безопасно, потому что сообщение идемпотентно по ключу».
> - «`http-error` — если живых реплик нет, сам LB отвечает JSON-ошибкой в формате API с `X-Request-Id`».
---
## 4. Публичный тест
```bash
make check
```
```bash
make test BASE_URL="$B"
```
> **Сказать:** «Публичный smoke lab3: всё из lab2 плюс обязательный `X-Instance-Id` в каждом ответе и `Idempotency-Key` при отправке сообщения — повтор, 409 на другой body, 400 без ключа».
---
## 5. Одна сессия — разные реплики
```bash
ALICE=$(curl -s -X POST "$B/api/v1/users" -H 'Content-Type: application/json' -d '{"username":"alice","display_name":"Алиса","password":"Alice-demo-pass-1"}' | j id); BOB=$(curl -s -X POST "$B/api/v1/users" -H 'Content-Type: application/json' -d '{"username":"bob","display_name":"Боб","password":"Bob-demo-pass-123"}' | j id); echo "$ALICE $BOB"
```
Один вход — один токен:
```bash
TA=$(curl -s -X POST -u 'alice:Alice-demo-pass-1' "$B/api/v1/auth/sessions" | j token); TB=$(curl -s -X POST -u 'bob:Bob-demo-pass-123' "$B/api/v1/auth/sessions" | j token); echo ok
```
Шесть запросов одним токеном:
```bash
for i in 1 2 3 4 5 6; do curl -s -D - -o /dev/null "$B/api/v1/users/me" -H "Authorization: Bearer $TA" | grep -i '^x-instance-id'; done
```
Какому контейнеру соответствует каждый id:
```bash
ids
```
> **Сказать:**
> - «Запросы чередуются между двумя репликами, а повторного входа нет: сессия хранится в PostgreSQL, кэш общий в Valkey. Ни у одной реплики нет своего локального состояния».
> - «`X-Instance-Id` — случайный псевдоним `api-xxxxxxxx`, генерируется один раз при старте процесса. Hostname и IP не раскрываются. Сама реплика пишет его в `/tmp/instance-id` своего контейнера — так я доказываю, что это разные процессы в разных контейнерах, а не просто разный заголовок».
---
## 6. Идемпотентность отправки
```bash
CHAT=$(curl -s -X POST "$B/api/v1/chats" -H 'Content-Type: application/json' -H "Authorization: Bearer $TA" -d "{\"title\":\"Защита ЛР3\",\"member_ids\":[\"$ALICE\",\"$BOB\"]}" | j id); KEY=demo-$(date +%s); echo "$CHAT $KEY"
```
Один и тот же POST три раза — смотрим id сообщения и реплику:
```bash
for i in 1 2 3; do curl -s -i -X POST "$B/api/v1/chats/$CHAT/messages" -H 'Content-Type: application/json' -H "Authorization: Bearer $TA" -H "Idempotency-Key: $KEY" -d '{"text":"Ровно одно сообщение"}' | grep -iE '^HTTP|^x-instance-id|"id"' ; echo; done
```
Тот же ключ, другой текст → 409; без ключа → 400:
```bash
curl -s -o /dev/null -w '%{http_code}\n' -X POST "$B/api/v1/chats/$CHAT/messages" -H 'Content-Type: application/json' -H "Authorization: Bearer $TA" -H "Idempotency-Key: $KEY" -d '{"text":"Другой текст"}'; curl -s -o /dev/null -w '%{http_code}\n' -X POST "$B/api/v1/chats/$CHAT/messages" -H 'Content-Type: application/json' -H "Authorization: Bearer $TA" -d '{"text":"без ключа"}'
```
Тот же ключ у Боба — независим:
```bash
curl -s -X POST "$B/api/v1/chats/$CHAT/messages" -H 'Content-Type: application/json' -H "Authorization: Bearer $TB" -H "Idempotency-Key: $KEY" -d '{"text":"Ровно одно сообщение"}'; echo
```
```bash
pg "SELECT key, user_id, encode(request_hash,'hex') AS hash, message_id, created_at FROM idempotency_keys WHERE chat_id = '$CHAT'"
```
```bash
pg "SELECT count(*) FROM messages WHERE chat_id = '$CHAT'"
```
> **Сказать:**
> - «Три одинаковых POST через разные реплики — один и тот же `201` и тот же `id`. Сообщений в базе от Алисы одно, плюс одно от Боба: ключ ограничен пользователем и чатом».
> - «Таблица `idempotency_keys`, первичный ключ `(user_id, chat_id, key)`. В ней SHA-256 канонического JSON тела (ключи отсортированы) — поэтому другой текст с тем же ключом даёт 409».
> - «Запись ключа и сообщения — **одна транзакция**: сначала `INSERT … ON CONFLICT DO NOTHING` в `idempotency_keys`, потом `INSERT` сообщения. Если транзакция упала, нет ни ключа, ни сообщения — клиент может безопасно повторить. Если она закоммичена, повтор получит сохранённый результат».
> - «Ключ хранится 24 часа (`IDEMPOTENCY_TTL_SECONDS`); устаревшая запись удаляется при следующем использовании этого ключа».
Конкурентный повтор через разные реплики — свой тест:
```bash
make test-student BASE_URL="$B"
```
> **Сказать:** «32 потока одновременно (через `threading.Barrier`) отправляют один и тот же ключ, 5 раундов. Запросы делятся по репликам 16/16, а сообщение создаётся ровно одно. Как это работает: второй `INSERT` с тем же первичным ключом **ждёт** на уникальном индексе, пока первая транзакция не закончится. После её COMMIT он получает конфликт, читает уже закоммиченную строку и возвращает то же сообщение. Гонку решает PostgreSQL, а не проверка "SELECT, потом INSERT"».
---
## 7. Отказ одной реплики
```bash
cat scripts/stop-one.sh
```
> **Сказать:** «Тест передаёт `TARGET_INSTANCE_ID` — id реплики, которая обслужила его первое сообщение. Скрипт обходит контейнеры `api`, читает `/tmp/instance-id` и делает `docker stop` **именно** нужного. `docker stop` шлёт SIGTERM, а `restart: unless-stopped` не поднимает контейнер, остановленный вручную, — реплика остаётся остановленной. БД, LB и volumes не трогаются».
```bash
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL="$B"
```
```bash
tail -1 evidence/stop-one.txt; docker compose ps -a api --format 'table {{.Name}}\t{{.Status}}'
```
> **Сказать:**
> - «Тест 15 секунд пишет сообщения параллельно со скриптом, неудачный POST повторяет **с тем же ключом**. Результат: `failed_attempts: 0`, запись восстановилась за ~3 с (норма ≤ 10 с), остановленная реплика в последних ответах не встречается, дублей и потерь нет».
> - «Видно, какой контейнер реально остановлен: `Exited (0)` — код 0, значит процесс корректно завершился по SIGTERM, а не был убит по таймауту (137)».
Возвращаем реплику:
```bash
make restore
```
Повторяем для **второй** реплики. Если в `stop-one.txt` снова та же — сдвигаем round-robin одним запросом и запускаем ещё раз:
```bash
curl -s -o /dev/null "$B/health/live"; make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL="$B"; tail -2 evidence/stop-one.txt
```
```bash
make restore
```
> **Сказать:** «Тест выбирает жертву по тому, кто ответил на его первое сообщение. Число запросов до этого у теста всегда одинаковое, а round-robin детерминирован — поэтому один лишний запрос меняет, какая реплика будет остановлена».
---
## 8. Рестарт всего стенда
```bash
cat scripts/restart.sh
```
```bash
docker inspect -f '{{.Name}} {{.State.StartedAt}}' $(docker compose ps -q)
```
```bash
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL="$B"
```
```bash
docker inspect -f '{{.Name}} {{.State.StartedAt}}' $(docker compose ps -q)
```
```bash
curl -s "$B/api/v1/chats/$CHAT/messages" -H "Authorization: Bearer $TA" | python3 -m json.tool --no-ensure-ascii | head -20
```
> **Сказать:** «`StartedAt` изменился у всех: api, lb, postgres, valkey. Volume `pgdata` тот же, поэтому прежний токен Алисы работает без повторного входа, и сообщения на месте».
---
## 9. Уровень 4: отказ каждой реплики под нагрузкой
```bash
make chaos BASE_URL="$B"
```
> **Сказать:**
> - «Мой генератор `student-tests/chaos_load.py`: 8 потоков 25 секунд, каждый по кругу пишет сообщение (неудачу повторяет с тем же ключом) и читает историю. На 5-й секунде `scripts/stop-container.sh` останавливает реплику. Make делает это по очереди для api-1 и api-2, восстанавливая предыдущую».
> - «На моём стенде: ~600 успешных RPS, **0 ошибок**, p99 ≈ 60 мс, восстановление ≈ 2.5 с. После прогона читается вся история: каждое подтверждённое сообщение есть ровно один раз».
> - «Худшая задержка ≈ 1 с: IP остановленного контейнера не отвечает отказом, HAProxy ждёт `timeout connect 1s` и повторяет запрос на живой реплике. Через ≤ 2 проверки реплика выводится из ротации, и задержки прекращаются».
> - «В `docker_stats_mid` видно: оставшаяся реплика упирается в свой лимит 0.5 CPU — это предел пропускной способности одной реплики».
## 10. Уровень 4: rolling update под нагрузкой
```bash
cat scripts/rolling-update.sh
```
```bash
python3 student-tests/chaos_load.py --base-url "$B" --action scripts/rolling-update.sh --action-at 5 --duration 45 | python3 -c 'import json,sys; d=json.load(sys.stdin); print({k: d[k] for k in ("requests","errors","successful_rps","latency_ms_success","action_output","integrity")})'
```
```bash
docker compose ps api --format 'table {{.Name}}\t{{.Status}}'
```
> **Сказать:**
> - «Compose сам не умеет поочерёдную замену, поэтому скрипт: собрать новый образ → один раз прогнать миграции → для каждой старой реплики поднять одну новую (`--scale N+1 --no-recreate`), дождаться `healthy`, затем остановить и удалить одну старую. В ротации никогда не меньше N рабочих реплик».
> - «Ошибок 0, реплики теперь `api-3` и `api-4` — это новые контейнеры».
> - «Миграции аддитивные: новая таблица `idempotency_keys` не мешает старой версии кода. Разрушающее изменение схемы потребовало бы expand/contract в несколько релизов».
## 11. Уровень 4: лимиты, изоляция, ответ LB без реплик
```bash
for c in $(docker compose ps -q); do docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} mem={{.HostConfig.Memory}}' $c; done
```
```bash
docker compose exec -T lb sh -c 'nc -z -w 2 postgres 5432 && echo reachable || echo "postgres недоступен из lb"'
```
Останавливаем обе реплики — отвечает сам LB:
```bash
docker compose stop api; sleep 3; curl -si "$B/api/v1/users/me"; echo
```
```bash
docker compose up -d --wait api
```
> **Сказать:** «503 в формате ошибок API с `X-Request-Id`, без `X-Instance-Id` — контракт это разрешает для ошибок, созданных самим LB».
---
## 12. Остановка и удаление данных
Обычная остановка, данные в volume остаются:
```bash
docker compose down
```
Намеренное удаление учебных данных демо-стенда (необратимо):
```bash
docker compose down -v
```
```bash
unset COMPOSE_PROJECT_NAME
```
---
## Короткие ответы на вопросы из README
- **Чем отказ процесса отличается от отказа узла?**
- Отказ процесса — упал или остановлен один контейнер API. Docker-host, сеть, БД и LB живы, другая реплика продолжает работу. Это то, что выдерживает мой стенд.
- Отказ узла — пропадает вся машина: все контейнеры на ней, включая единственные LB и PostgreSQL. На одном Docker-host от этого не защититься: нужны несколько узлов, реплицированная БД, LB вне узла (трек 2 уровня 5, его я не делал).
- **Почему `depends_on`/healthcheck сами по себе не являются балансировщиком?**
- `depends_on` управляет только **порядком запуска** при `up`. После старта он ничего не делает.
- Healthcheck Docker только помечает контейнер `unhealthy`; трафик он не перенаправляет и сам контейнер в Compose не перезапускает.
- Распределять запросы, исключать мёртвые бэкенды и повторять запрос на другом умеет только балансировщик — у меня HAProxy с собственными активными проверками.
- **Какие POST можно повторять после timeout и что защищает Idempotency-Key?**
- После timeout клиент не знает, выполнилась ли запись. Повторять можно только идемпотентные операции. У нас это `POST /chats/{id}/messages` **с тем же ключом и тем же телом**: если первая попытка закоммичена, сервер вернёт её результат, если нет — выполнит заново.
- Ключ защищает от дублей при повторе клиентом, при повторе LB на другой реплике и при одновременных повторах.
- Создание чата, регистрацию, загрузку файла слепо повторять нельзя: ключа у них нет, получится второй объект.
- **Что сломается при увеличении числа API, если сессии хранятся в локальной памяти?**
- Токен знает только реплика, где был вход. Round-robin отправит следующий запрос на другую — `401`. Пришлось бы включать sticky sessions, а это маскирует проблему.
- Logout на одной реплике не отзовёт токен на другой.
- При остановке или перезапуске реплики все её сессии пропадут, пользователям придётся входить заново.
- Аналогично для локальных ключей идемпотентности: повтор через другую реплику создал бы дубль.
+23
View File
@@ -0,0 +1,23 @@
FROM python:3.12.8-slim-bookworm
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
COPY migrations ./migrations
RUN useradd --system --no-create-home --uid 10001 appuser
USER appuser
ENV APP_HOST=0.0.0.0 \
APP_PORT=8080 \
PYTHONUNBUFFERED=1
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD python -c "import os,urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:'+os.environ.get('APP_PORT','8080')+'/health/ready',timeout=2).status==200 else 1)"
CMD ["sh", "-c", "exec uvicorn app.main:app --host ${APP_HOST} --port ${APP_PORT} --timeout-graceful-shutdown 8 --timeout-keep-alive 30"]
+26 -1
View File
@@ -4,7 +4,7 @@ CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover
.PHONY: help check validate test load test-persistence test-failover secrets up down restore rolling-update test-student chaos
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@@ -28,3 +28,28 @@ test-persistence:
test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
secrets:
sh scripts/init-secrets.sh
up: secrets
docker compose up -d --build --wait
down:
docker compose down
restore:
sh scripts/restore.sh
rolling-update:
sh scripts/rolling-update.sh
test-student:
$(PYTHON) student-tests/idempotency_test.py --base-url "$(BASE_URL)"
chaos:
@for n in 1 2; do \
name=$$(docker compose ps --format '{{.Name}}' api | sed -n "$${n}p"); \
$(PYTHON) student-tests/chaos_load.py --base-url "$(BASE_URL)" --action "scripts/stop-container.sh $$name" --output evidence/failover-load/stop-api-$$n.json | $(PYTHON) -c 'import json,sys; d=json.load(sys.stdin); print(json.dumps({k: d[k] for k in ("action_output","requests","errors","successful_rps","latency_ms_success","recovery_s_after_action","instances_last_5s","docker_stats_mid","integrity")},ensure_ascii=False,indent=1))'; \
sh scripts/restore.sh >/dev/null 2>&1; sleep 3; \
done
+82 -16
View File
@@ -1,37 +1,103 @@
# Отчёт — лабораторная 3
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор, группа: Кошелев, БВТ2304
- Целевая оценка: **4** (трек 5 не заявлен)
- Commit/PR: ветка `solution/bvt2304-koshelev`, PR в `mtusi2026/mtusi2026lab3` (main)
- Использованные источники, библиотеки и помощь ИИ: FastAPI, uvicorn, pydantic, asyncpg, redis-py (клиент Valkey), argon2-cffi; HAProxy 3.2 (документация: `server-template`, `resolvers`, `http-check`, `retry-on`, `http-error`), Docker Compose reference (`deploy.replicas`, `resources`), PostgreSQL `INSERT … ON CONFLICT`. Код перенесён из собственной lab2. При доработке, тестах и отчёте использовался ИИ-ассистент Claude (Anthropic); решения проверены и объяснимы автором.
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Требования: Docker Engine + Compose v2 (проверено: Docker Desktop 28.0.1, Compose 2.33.1), Python 3.9+ для тестов (проверено 3.14), `make`. Стенд: Apple M3, 8 CPU, Docker VM 8 CPU / 7.6 GiB.
| Роль | Service | Образ | Health/readiness | Volume | Сеть / порт | Credentials |
| --- | --- | --- | --- | --- | --- | --- |
| Балансировщик | `lb` | `haproxy:3.2.4-alpine` | `monitor-uri /lb-health` (внутр. 127.0.0.1:8405) | — | `edge`; **единственный опубликованный порт** `127.0.0.1:${APP_PORT:-8080}` | нет |
| API × N | `api` (`deploy.replicas: ${API_REPLICAS:-2}`) | `mtusi-messenger:lab3` (сборка из `Dockerfile`, база `python:3.12.8-slim-bookworm`) | `/health/ready` (SELECT 1 в PostgreSQL) | нет локального состояния | `edge` + `data`, порт 8080 **не публикуется** | secrets `database_url`, `cache_url` |
| Миграции | `migrate` (one-shot) | `mtusi-messenger:lab3` | exit 0 | — | `data` | secret `database_url` |
| БД (источник истины) | `postgres` | `postgres:17.6-alpine3.22` | `pg_isready` | `pgdata` | `data` (internal) | secret `postgres_password` |
| Кэш сессий | `valkey` | `valkey/valkey:8.1.4-alpine3.22` | `valkey-cli ping` | нет (только кэш) | `data` (internal) | secret `valkey_conf` (requirepass) |
```sh
./scripts/init-secrets.sh # создаёт ./secrets/* (в .gitignore), значения не печатаются
cp .env.example .env # при занятом 8080 поменяйте APP_PORT в .env (у автора: 8088)
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait # postgres/valkey -> migrate -> api x2 -> lb
make test # BASE_URL=http://localhost:8088 при другом порту
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
./scripts/restore.sh # вернуть остановленную реплику
make test-student # конкурентная идемпотентность через обе реплики
make chaos # поочерёдная остановка каждой реплики под нагрузкой
```
- Короткие цели: `make secrets`, `make up` (= secrets + `up -d --build --wait`), `make restore`, `make rolling-update`, `make down`. Пошаговый сценарий защиты с командами — [DEMO.md](DEMO.md).
- Масштабирование: `API_REPLICAS=4 docker compose up -d --wait` (LB подхватывает новые адреса через DNS, до 8 слотов).
- Rolling update: `./scripts/rolling-update.sh`.
- Безопасная остановка: `docker compose stop` (или `down` — volumes сохраняются).
- **Намеренное удаление учебных данных:** `docker compose down -v` (удаляет volume `pgdata`; только осознанно).
Соответствие `.env.example`: `APP_HOST`/`APP_PORT` — адрес uvicorn внутри контейнера (в контейнере всегда 8080), `APP_PORT` в `.env` — опубликованный порт LB; `SESSION_TTL_SECONDS` → API; `DATABASE_URL_FILE`, `CACHE_URL_FILE` → Docker secrets; `SESSION_STORE=postgres` (Valkey — только кэш); `API_REPLICAS` → `deploy.replicas`; `IDEMPOTENCY_TTL_SECONDS` → API (по умолчанию 86400).
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
```
client ──► lb (HAProxy, :8080) ──round-robin──► api-1 ┐
└──────────────► api-2 ┼──► postgres (users, chats, messages, sessions, idempotency_keys)
сеть edge └──► valkey (кэш сессий + tombstone отзыва) сеть data (internal)
```
**Из lab2 перенесено:** FastAPI-приложение, PostgreSQL как источник истины, сессии в PostgreSQL (hash токена, expiry), Valkey как общий кэш сессий с tombstone при logout, Argon2id, отдельный сервис миграций с advisory lock.
**Изменено в lab3:**
1. **Нет локального состояния в API.** Сессии/сообщения/ключи идемпотентности — в PostgreSQL, кэш — общий Valkey. Единственное in-memory — краткий список «незаписанных tombstone» при сбое Valkey, он лишь ужесточает проверку (кэш обходится, решение принимает БД). Поэтому sticky sessions не нужны и **не используются**: один токен обслуживают обе реплики (`evidence/topology.txt`).
2. **`X-Instance-Id`.** Случайный alias `api-xxxxxxxx`, генерируется при старте процесса (без hostname/IP), добавляется middleware к каждому ответу, включая ошибки и health. Alias пишется в `/tmp/instance-id` в контейнере — так `scripts/stop-one.sh` сопоставляет `TARGET_INSTANCE_ID` с контейнером через `docker exec`.
3. **Идемпотентность** (`migrations/0002_idempotency.sql`, `Store.create_message`). Таблица `idempotency_keys(user_id, chat_id, key)` — PK = пользователь + путь чата + ключ (метод один — POST messages). В **одной транзакции**: удалить запись этого ключа старше `IDEMPOTENCY_TTL_SECONDS` → `INSERT … ON CONFLICT DO NOTHING` (захват ключа, тут же проверка членства) → `INSERT` сообщения (FK на сообщение `DEFERRABLE INITIALLY DEFERRED`). Конкурентный дубль блокируется на уникальном индексе до COMMIT/ROLLBACK первого; затем читает зафиксированный результат новым снимком (READ COMMITTED) и возвращает тот же `201 Message`. Отпечаток тела — SHA-256 канонического JSON (сортировка ключей), другой body → 409. Сбой/таймаут до COMMIT не оставляет ни ключа, ни сообщения → повтор безопасен; после COMMIT повтор получает сохранённый результат. Повтор заново проходит аутентификацию и проверку членства (JOIN с `chat_members`).
4. **Миграции** — только one-shot сервис `migrate`; `api` стартует по `service_completed_successfully`. Реплики схему не трогают, гонки нет. `0002` аддитивна: старый код lab2 работает на новой схеме.
5. **LB (HAProxy):** адреса реплик из Docker DNS (`server-template api 8 api:8080 resolvers docker`, `hold valid 2s`) — масштабирование и пересоздание контейнеров без reload. Активная проверка `GET /health/ready`: `inter 1s, fall 2, rise 2, timeout check 1s`. `timeout connect 1s`, `retries 3`, `option redispatch 1`, `retry-on conn-failure empty-response` — неудавшееся соединение повторяется на **другой** реплике. Ошибки, созданные самим LB (502/503/504), имеют JSON-формат API и `X-Request-Id` (`evidence/lb-no-backends.txt`).
6. **Graceful shutdown:** `uvicorn` — PID 1 (`exec`), по SIGTERM сразу закрывает listen-сокет (новые соединения → refused → LB повторяет на другой реплике), дорабатывает начатые запросы до 8 с (`--timeout-graceful-shutdown 8`), `stop_grace_period: 10s` > 8 с. Keep-alive uvicorn 30 с > idle-пул HAProxy, чтобы не было гонки переиспользования закрытого соединения.
**Тайминги обнаружения отказа:** health-check каждые 1 с, сервер выводится после 2 неудач → ≤ ~3 с (2 × (1 с интервал) + 1 с таймаут). Остановленный контейнер также пропадает из DNS (hold 2 с). До этого запросы к нему получают таймаут соединения 1 с и повторяются на другой реплике — поэтому наблюдаемые пики латентности ≈1 с, но без ошибок.
**Транзакционные границы:** сообщение + ключ идемпотентности — одна транзакция; создание чата + участники — одна транзакция; логин/logout — одна строка `sessions` (+ tombstone в Valkey; при сбое Valkey logout отвечает 503 и ретраит tombstone в фоне).
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Публичный smoke | `make test` через LB | PASS lab3 | `evidence/smoke.txt` |
| Стенд в compose.yaml, ≥2 API, одна точка входа, общие БД и сессии | `docker compose up -d --build --wait`; `docker compose ps` | 2 × api, порт опубликован только у lb | `evidence/topology.txt` |
| Разные запросы одной сессии — разные реплики без повторного входа | 6 × `GET /users/me` одним токеном | X-Instance-Id чередуется `api-255e07d5`/`api-624de536` | `evidence/topology.txt` |
| Остановка любой реплики, записи ≤10 с | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` ×6 + `restore.sh` | PASS все 6 раз; 0 ошибок, восстановление 1.6–3.4 с; остановлены и api-2, и api-1 | `evidence/failover.txt`, `evidence/stop-one.txt` |
| Повтор POST с тем же ключом без дубля, в т.ч. конкурентно и через другую реплику | `student-tests/idempotency_test.py` | 5 раундов × 32 одновременных запроса (16/16 по репликам) → ровно 1 сообщение; другой body → 409; область ключа user+chat; 400 на плохой ключ; 401/404 при повторе | `evidence/idempotency.txt` |
| Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS; StartedAt изменился у api, lb, postgres, valkey; volume `pgdata` тот же; токен прежний | `evidence/persistence.txt` |
| (4) health/readiness, timeouts, SIGTERM, LB исключает backend | конфиг `infra/haproxy/haproxy.cfg`, `Dockerfile` | период проверки 1 с, обнаружение ≤ ~3 с; после стопа последние ответы только от живой реплики | `evidence/failover-load/*.json` (`instances_last_5s`) |
| (4) Поочерёдная остановка каждой реплики под нагрузкой: RPS, ошибки, восстановление | `chaos_load.py --action "scripts/stop-container.sh messenger-lab3-api-N"` | см. таблицу ниже | `evidence/failover-load/stop-api-1.json`, `stop-api-2.json` |
| (4) CPU/RAM-лимиты, нет портов API, нет container_name, data-сеть internal | `docker inspect`, `compose.yaml` | api 0.5 CPU/256M, pg 1 CPU/512M, valkey 0.25/96M, lb 0.5/128M; postgres недоступен из lb | `evidence/topology.txt` |
| (4) Rolling update под нагрузкой, однократные совместимые миграции | `chaos_load.py --action scripts/rolling-update.sh` | api-1,2 заменены на api-3,4 по одной; 0 ошибок из 41 154 запросов | `evidence/rolling-update-load.json` |
| Базовая нагрузка | `tests/load.py --duration 30 --concurrency 4` | 840.8 успешных RPS, 0 ошибок, p50/p95/p99 = 4.4/6.4/10.3 мс | `evidence/load.json` |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Методика: `student-tests/chaos_load.py`, closed loop, 8 потоков; каждый поток по кругу делает `POST message` (неподтверждённый POST повторяется **с тем же ключом и телом**) и `GET history?limit=20`, таймаут клиента 2 с. Действие запускается на 5-й секунде. После прогона вся история читается и сверяется: каждое подтверждённое сообщение есть ровно один раз, дублей текста нет. Лимиты — как в таблице выше; набор данных — новый чат на каждый прогон (7–20 тыс. сообщений). Один прогон на сценарий: это демонстрация, не статистическое исследование.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
| `docker stop` api-1 под нагрузкой | краткие ошибки/задержки, затем всё на api-2 | 15 020 запросов, **0 ошибок**, 600 RPS, p50/p95/p99 = 7.9/45/59 мс, max 1019 мс (16 запросов > 0.5 с) | ≤ 2.7 с; потерь и дублей нет |
| `docker stop` api-2 под нагрузкой | то же | 15 264 запросов, **0 ошибок**, 610 RPS, p99 57 мс, max 1020 мс | ≤ 2.5 с; потерь и дублей нет |
| Rolling update (N→N+1→N, дважды) | без ошибок | 41 154 запросов, **0 ошибок**, 823 RPS, p99 54 мс, max 1023 мс | пики ≈1 с в момент каждой остановки; потерь нет |
| Публичный failover-тест ×6 | запись ≤10 с | 0 failed attempts, first_recovery 1.6–3.4 с (время включает выполнение hook ≈0.6–0.9 с) | данные и токен сохранены |
| Рестарт всего стенда | данные и сессия живы | PASS | ≈7 с; потерь нет |
| Обе реплики остановлены | LB отвечает сам | `503` JSON `unavailable` с `X-Request-Id` | до `restore.sh` |
Объяснение пиков ≈1 с: IP остановленного контейнера не отвечает RST, поэтому первый запрос к нему ждёт `timeout connect 1s`, после чего HAProxy повторяет его на другой реплике (`redispatch`). Через ≤ 2 health-check сервер выводится из ротации, и пики прекращаются. CPU во время отказа: оставшаяся реплика ~51% (из лимита 0.5 CPU — упирается в лимит), PostgreSQL 21–30%, LB 13%.
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Выдерживается отказ **одного процесса/контейнера API**. Не выдерживаются: отказ PostgreSQL, отказ LB, отказ Docker-host — это единые точки отказа (один узел, одна БД без реплики, один HAProxy).
- Valkey без persistence: его рестарт лишь сбрасывает кэш, источник истины — PostgreSQL. При недоступности Valkey API работает через БД, но logout отвечает 503, пока tombstone не записан.
- Задержка до 1 с у части запросов во время отказа: можно уменьшить `timeout connect` или добавить pre-stop drain (readiness 503 → пауза → SIGTERM); не сделано, т.к. ошибок нет и цель ≤10 с выполняется с запасом.
- Очистка истёкших ключей идемпотентности выполняется лениво (при повторе того же ключа); фоновой очистки таблицы нет — для учебного объёма достаточно, есть индекс `created_at` для будущего batch-удаления.
- Миграции совместимы только при аддитивных изменениях; разрушающая миграция потребовала бы expand/contract в несколько релизов.
- `scripts/rolling-update.sh` — эквивалент rolling update для Compose (Compose сам не умеет поочерёдную замену), использует `--scale N+1` и `docker stop`/`rm` старых контейнеров; после него контейнеры называются `api-3`, `api-4` — это нормально.
- Тестовый порт у автора 8088, т.к. 8080 занят посторонним контейнером; конфигурация по умолчанию — 8080.
View File
+113
View File
@@ -0,0 +1,113 @@
from __future__ import annotations
import asyncio
import base64
import binascii
import hashlib
import secrets
from datetime import datetime, timezone
from typing import Optional, Tuple
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from starlette.concurrency import run_in_threadpool
from app import config
from app.cache import REVOKED, SessionCache
from app.errors import BASIC_CHALLENGE, ApiError, unauthorized
from app.storage import Store, fmt_ts, user_row
_hasher = PasswordHasher()
_hash_slots = asyncio.Semaphore(config.PASSWORD_HASH_CONCURRENCY)
_DUMMY_HASH = _hasher.hash("dummy-password-for-timing")
async def hash_password(password: str) -> str:
async with _hash_slots:
return await run_in_threadpool(_hasher.hash, password)
async def verify_password(password_hash: str, password: str) -> bool:
def verify() -> bool:
try:
return _hasher.verify(password_hash, password)
except (VerificationError, InvalidHashError):
return False
async with _hash_slots:
return await run_in_threadpool(verify)
def token_digest(token: str) -> bytes:
return hashlib.sha256(token.encode("ascii")).digest()
def parse_basic(header: Optional[str]) -> Tuple[str, str]:
bad = unauthorized("invalid credentials", BASIC_CHALLENGE)
if not header:
raise bad
scheme, _, value = header.partition(" ")
if scheme.lower() != "basic" or not value.strip():
raise bad
try:
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
except (binascii.Error, UnicodeDecodeError):
raise bad from None
username, sep, password = decoded.partition(":")
if not sep or not username.isascii() or not 12 <= len(password) <= 128:
raise bad
return username, password
def parse_bearer(header: Optional[str]) -> str:
if not header:
raise unauthorized("bearer token required")
scheme, _, token = header.partition(" ")
token = token.strip()
if scheme.lower() != "bearer" or not token or not token.isascii() or len(token) > 256:
raise unauthorized("bearer token required")
return token
async def login(store: Store, header: Optional[str]) -> dict:
username, password = parse_basic(header)
row = await store.get_credentials(username)
if row is None:
await verify_password(_DUMMY_HASH, password)
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
if not await verify_password(row["password_hash"], password):
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
token = secrets.token_urlsafe(32)
expires_at = await store.create_session(token_digest(token), row["id"], config.SESSION_TTL_SECONDS)
return {"token": token, "token_type": "Bearer", "expires_at": fmt_ts(expires_at), "user": user_row(row)}
async def authenticate(store: Store, cache: SessionCache, header: Optional[str]) -> dict:
digest = token_digest(parse_bearer(header))
cached = await cache.get(digest)
if cached == REVOKED:
raise unauthorized("session expired or revoked")
if isinstance(cached, dict):
expires_at = datetime.fromisoformat(cached["expires_at"].replace("Z", "+00:00"))
if expires_at > datetime.now(timezone.utc):
return cached["user"]
raise unauthorized("session expired or revoked")
row = await store.find_session(digest)
if row is None:
raise unauthorized("session expired or revoked")
user = user_row(row)
remaining = int((row["expires_at"] - datetime.now(timezone.utc)).total_seconds())
await cache.put(digest, {"user": user, "expires_at": fmt_ts(row["expires_at"])}, remaining)
return user
async def logout(store: Store, cache: SessionCache, header: Optional[str]) -> None:
await authenticate(store, cache, header)
digest = token_digest(parse_bearer(header))
expires_at = await store.revoke_session(digest)
if expires_at is None:
raise unauthorized("session expired or revoked")
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1
if not await cache.revoke(digest, remaining):
raise ApiError(503, "unavailable", "logout not confirmed by session cache, retry later")
+125
View File
@@ -0,0 +1,125 @@
from __future__ import annotations
import asyncio
import json
import logging
import time
from typing import Dict, Optional, Set, Union
import redis.asyncio as redis
from redis.exceptions import RedisError
from app import config
logger = logging.getLogger("messenger.cache")
REVOKED = "revoked"
class SessionCache:
def __init__(self, url: Optional[str]):
self._client: Optional[redis.Redis] = None
self._down_until = 0.0
self._pending_revokes: Dict[bytes, float] = {}
self._retry_tasks: Set[asyncio.Task] = set()
if url:
pool = redis.BlockingConnectionPool.from_url(
url,
max_connections=config.CACHE_POOL_MAX,
timeout=config.CACHE_TIMEOUT,
socket_timeout=config.CACHE_TIMEOUT,
socket_connect_timeout=config.CACHE_TIMEOUT,
decode_responses=True,
)
self._client = redis.Redis(connection_pool=pool)
@property
def enabled(self) -> bool:
return self._client is not None
def _usable(self) -> bool:
return self._client is not None and time.monotonic() >= self._down_until
def _failed(self, op: str, exc: Exception) -> None:
self._down_until = time.monotonic() + config.CACHE_RETRY_AFTER
logger.warning("cache %s failed (%s); bypassing cache for %.0fs", op, type(exc).__name__, config.CACHE_RETRY_AFTER)
@staticmethod
def _key(token_hash: bytes) -> str:
return "session:" + token_hash.hex()
def _revoke_pending(self, token_hash: bytes) -> bool:
deadline = self._pending_revokes.get(token_hash)
if deadline is None:
return False
if time.monotonic() >= deadline:
self._pending_revokes.pop(token_hash, None)
return False
return True
async def get(self, token_hash: bytes) -> Union[dict, str, None]:
if not self._usable() or self._revoke_pending(token_hash):
return None
try:
raw = await self._client.get(self._key(token_hash))
except (RedisError, OSError) as exc:
self._failed("get", exc)
return None
if raw is None or raw == REVOKED:
return raw
try:
return json.loads(raw)
except ValueError:
return None
async def put(self, token_hash: bytes, entry: dict, ttl_seconds: int) -> None:
ttl = min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)
if ttl <= 0 or not self._usable():
return
try:
await self._client.set(self._key(token_hash), json.dumps(entry), ex=ttl, nx=True)
except (RedisError, OSError) as exc:
self._failed("set", exc)
async def _write_tombstone(self, token_hash: bytes, ttl_seconds: int) -> bool:
try:
await self._client.set(self._key(token_hash), REVOKED, ex=max(1, min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)))
return True
except (RedisError, OSError) as exc:
self._failed("revoke", exc)
return False
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> bool:
if self._client is None:
return True
if await self._write_tombstone(token_hash, ttl_seconds):
return True
deadline = time.monotonic() + config.SESSION_CACHE_MAX_SECONDS + 1
self._pending_revokes[token_hash] = deadline
task = asyncio.create_task(self._retry_revoke(token_hash, ttl_seconds, deadline))
self._retry_tasks.add(task)
task.add_done_callback(self._retry_tasks.discard)
return False
async def _retry_revoke(self, token_hash: bytes, ttl_seconds: int, deadline: float) -> None:
while time.monotonic() < deadline:
await asyncio.sleep(1)
remaining = int(deadline - time.monotonic())
if remaining > 0 and await self._write_tombstone(token_hash, min(ttl_seconds, remaining)):
logger.info("revocation tombstone written after cache recovery")
break
self._pending_revokes.pop(token_hash, None)
async def ping(self) -> bool:
if self._client is None:
return False
try:
return bool(await self._client.ping())
except (RedisError, OSError):
return False
async def close(self) -> None:
for task in list(self._retry_tasks):
task.cancel()
if self._client is not None:
await self._client.aclose()
+47
View File
@@ -0,0 +1,47 @@
from __future__ import annotations
import os
import secrets
from typing import Optional
def _secret(name: str) -> Optional[str]:
value = os.environ.get(name)
if value:
return value.strip()
path = os.environ.get(name + "_FILE")
if path and os.path.exists(path):
with open(path, encoding="utf-8") as fh:
return fh.read().strip() or None
return None
def _int(name: str, default: int) -> int:
return int(os.environ.get(name, default))
def _float(name: str, default: float) -> float:
return float(os.environ.get(name, default))
DATABASE_URL = _secret("DATABASE_URL")
CACHE_URL = _secret("CACHE_URL")
SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600)
SESSION_CACHE_MAX_SECONDS = _int("SESSION_CACHE_MAX_SECONDS", 300)
DB_POOL_MAX = _int("DB_POOL_MAX", 10)
DB_CONNECT_TIMEOUT = _float("DB_CONNECT_TIMEOUT", 3)
DB_ACQUIRE_TIMEOUT = _float("DB_ACQUIRE_TIMEOUT", 3)
DB_COMMAND_TIMEOUT = _float("DB_COMMAND_TIMEOUT", 5)
CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.3)
CACHE_POOL_MAX = _int("CACHE_POOL_MAX", 20)
CACHE_RETRY_AFTER = _float("CACHE_RETRY_AFTER", 5)
PASSWORD_HASH_CONCURRENCY = _int("PASSWORD_HASH_CONCURRENCY", 4)
IDEMPOTENCY_TTL_SECONDS = _int("IDEMPOTENCY_TTL_SECONDS", 86400)
INSTANCE_ID = "api-" + secrets.token_hex(4)
INSTANCE_ID_FILE = os.environ.get("INSTANCE_ID_FILE", "/tmp/instance-id")
+23
View File
@@ -0,0 +1,23 @@
from __future__ import annotations
from typing import Dict, Optional
BEARER_CHALLENGE = 'Bearer realm="messenger"'
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
class ApiError(Exception):
def __init__(self, status_code: int, code: str, message: str, headers: Optional[Dict[str, str]] = None):
super().__init__(message)
self.status_code = status_code
self.code = code
self.message = message
self.headers = headers or {}
def unauthorized(message: str, challenge: str = BEARER_CHALLENGE) -> ApiError:
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
def unavailable() -> ApiError:
return ApiError(503, "unavailable", "service temporarily unavailable")
+224
View File
@@ -0,0 +1,224 @@
from __future__ import annotations
import hashlib
import json
import logging
import re
import uuid
from contextlib import asynccontextmanager
from typing import Optional
import asyncpg
from fastapi import Depends, FastAPI, Header, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from app import auth, config
from app.cache import SessionCache
from app.errors import ApiError
from app.models import Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Health, Message, MessagePage, Session, User
from app.storage import Store
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("messenger")
store = Store()
cache = SessionCache(config.CACHE_URL)
@asynccontextmanager
async def lifespan(_app: FastAPI):
if not config.DATABASE_URL:
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
await store.open()
logger.info("session cache: %s", "valkey" if cache.enabled else "disabled")
try:
with open(config.INSTANCE_ID_FILE, "w", encoding="ascii") as fh:
fh.write(config.INSTANCE_ID + "\n")
except OSError:
logger.warning("cannot write %s", config.INSTANCE_ID_FILE)
logger.info("instance id: %s", config.INSTANCE_ID)
yield
await cache.close()
await store.close()
app = FastAPI(title="MTUSI Messenger — lab3", lifespan=lifespan)
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
DB_UNAVAILABLE = (
OSError,
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.TooManyConnectionsError,
asyncpg.exceptions.OperatorInterventionError,
asyncpg.exceptions.QueryCanceledError,
)
def error_body(code: str, message: str, request_id: str) -> dict:
return {"error": {"code": code, "message": message, "request_id": request_id}}
def error_response(request: Request, status: int, code: str, message: str, headers: Optional[dict] = None) -> JSONResponse:
request_id = getattr(request.state, "request_id", "")
return JSONResponse(status_code=status, content=error_body(code, message, request_id), headers=headers)
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request_id = uuid.uuid4().hex
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
logger.exception("unhandled error for request_id=%s", request_id)
response = JSONResponse(status_code=500, content=error_body("internal_error", "internal error", request_id))
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = config.INSTANCE_ID
return response
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return error_response(request, exc.status_code, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "request failed validation")
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
code = {404: "not_found", 405: "invalid_request", 415: "unsupported_media_type"}.get(exc.status_code, "invalid_request")
message = exc.detail if isinstance(exc.detail, str) else "request failed"
return error_response(request, exc.status_code, code, message)
async def db_unavailable_handler(request: Request, exc: Exception):
logger.warning("database unavailable for request_id=%s: %s", request.state.request_id, type(exc).__name__)
return error_response(request, 503, "unavailable", "service temporarily unavailable")
for _exc in DB_UNAVAILABLE:
app.add_exception_handler(_exc, db_unavailable_handler)
async def current_user(request: Request) -> dict:
return await auth.authenticate(store, cache, request.headers.get("Authorization"))
def parse_uuid(value: str, field: str) -> uuid.UUID:
try:
return uuid.UUID(value)
except ValueError:
raise ApiError(400, "invalid_request", f"{field} is not a valid UUID") from None
def not_found() -> ApiError:
return ApiError(404, "not_found", "chat not found")
@app.get("/health/live", response_model=Health)
async def liveness():
return Health()
@app.get("/health/ready", response_model=Health)
async def readiness():
try:
await store.ping()
except DB_UNAVAILABLE:
raise ApiError(503, "unavailable", "database is not available") from None
return Health()
@app.post("/api/v1/users", response_model=User, status_code=201)
async def register_user(body: CreateUser):
if not body.display_name.strip() or not body.password.strip():
raise ApiError(400, "invalid_request", "display_name and password must not be blank")
password_hash = await auth.hash_password(body.password)
return await store.create_user(body.username, body.display_name, password_hash)
@app.get("/api/v1/users/me", response_model=User)
async def current_user_endpoint(user: dict = Depends(current_user)):
return user
@app.post("/api/v1/auth/sessions", response_model=Session, status_code=201)
async def create_session(request: Request):
return await auth.login(store, request.headers.get("Authorization"))
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def delete_session(request: Request):
await auth.logout(store, cache, request.headers.get("Authorization"))
return Response(status_code=204)
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
if not body.title.strip():
raise ApiError(400, "invalid_request", "title must not be blank")
if len(set(body.member_ids)) != len(body.member_ids):
raise ApiError(400, "invalid_request", "member_ids must not contain duplicates")
if uuid.UUID(user["id"]) not in body.member_ids:
raise ApiError(400, "invalid_request", "caller must be a member of the chat")
return await store.create_chat(body.title, list(body.member_ids))
@app.get("/api/v1/chats", response_model=ChatPage)
async def list_chats(
user: dict = Depends(current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None, min_length=1),
):
return await store.list_chats(uuid.UUID(user["id"]), limit, cursor)
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
async def get_chat(chat_id: str, user: dict = Depends(current_user)):
chat = await store.get_chat_for_member(parse_uuid(chat_id, "chat_id"), uuid.UUID(user["id"]))
if chat is None:
raise not_found()
return chat
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def create_message(
chat_id: str,
body: CreateMessage,
user: dict = Depends(current_user),
idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key"),
):
chat_uuid = parse_uuid(chat_id, "chat_id")
if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
raise ApiError(400, "invalid_request", "Idempotency-Key header is required: [A-Za-z0-9._:-]{1,128}")
if not body.text.strip():
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
raise not_found()
raise ApiError(400, "invalid_request", "text must not be blank")
canonical = json.dumps(body.model_dump(mode="json"), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
request_hash = hashlib.sha256(canonical.encode("utf-8")).digest()
message = await store.create_message(chat_uuid, uuid.UUID(user["id"]), body.text, idempotency_key, request_hash)
if message is None:
raise not_found()
return message
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
async def list_messages(
chat_id: str,
user: dict = Depends(current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None, min_length=1),
):
chat_uuid = parse_uuid(chat_id, "chat_id")
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
raise not_found()
return await store.list_messages(chat_uuid, limit, cursor)
+63
View File
@@ -0,0 +1,63 @@
from __future__ import annotations
import asyncio
import logging
import sys
from pathlib import Path
import asyncpg
from app import config
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("migrate")
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
LOCK_ID = 2026_0002
async def connect_with_retry(attempts: int = 30) -> asyncpg.Connection:
for attempt in range(1, attempts + 1):
try:
return await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT)
except (OSError, asyncpg.PostgresError, asyncpg.InterfaceError) as exc:
logger.warning("database not reachable (attempt %d/%d): %s", attempt, attempts, type(exc).__name__)
await asyncio.sleep(1)
raise SystemExit("database is not reachable")
async def migrate() -> int:
if not config.DATABASE_URL:
raise SystemExit("DATABASE_URL or DATABASE_URL_FILE is required")
conn = await connect_with_retry()
applied_now = 0
try:
await conn.execute("SELECT pg_advisory_lock($1)", LOCK_ID)
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
done = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")}
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
version = path.stem
if version in done:
continue
logger.info("applying %s", version)
async with conn.transaction():
await conn.execute(path.read_text(encoding="utf-8"))
await conn.execute("INSERT INTO schema_migrations (version) VALUES ($1)", version)
applied_now += 1
logger.info("migrations up to date: %d applied now, %d before", applied_now, len(done))
finally:
await conn.execute("SELECT pg_advisory_unlock($1)", LOCK_ID)
await conn.close()
return applied_now
if __name__ == "__main__":
asyncio.run(migrate())
sys.exit(0)
+72
View File
@@ -0,0 +1,72 @@
from __future__ import annotations
import uuid
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
USERNAME_PATTERN = r"^[a-z0-9_]{3,32}$"
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(pattern=USERNAME_PATTERN)
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
class User(BaseModel):
id: uuid.UUID
username: str
display_name: str
created_at: str
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: List[uuid.UUID] = Field(min_length=1, max_length=100)
class Chat(BaseModel):
id: uuid.UUID
title: str
member_ids: List[uuid.UUID]
created_at: str
class ChatPage(BaseModel):
items: List[Chat]
next_cursor: Optional[str] = None
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(max_length=4000)
class Message(BaseModel):
id: uuid.UUID
chat_id: uuid.UUID
sender_id: uuid.UUID
text: str
created_at: str
class MessagePage(BaseModel):
items: List[Message]
next_cursor: Optional[str] = None
class Session(BaseModel):
token: str
token_type: str = "Bearer"
expires_at: str
user: User
class Health(BaseModel):
status: str = "ok"
+313
View File
@@ -0,0 +1,313 @@
from __future__ import annotations
import base64
import json
import uuid
from datetime import datetime, timezone
from typing import List, Optional, Tuple
import asyncpg
from app import config
from app.errors import ApiError
def fmt_ts(value: datetime) -> str:
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def user_row(row: asyncpg.Record) -> dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": fmt_ts(row["created_at"]),
}
def chat_row(row: asyncpg.Record) -> dict:
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(m) for m in row["member_ids"]],
"created_at": fmt_ts(row["created_at"]),
}
def message_row(row: asyncpg.Record) -> dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": fmt_ts(row["created_at"]),
}
def encode_cursor(resource: str, created_at: str, item_id: str) -> str:
payload = json.dumps({"r": resource, "t": created_at, "i": item_id}, separators=(",", ":"))
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
def decode_cursor(resource: str, cursor: str) -> Tuple[datetime, uuid.UUID]:
try:
padded = cursor + "=" * (-len(cursor) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
if payload.get("r") != resource:
raise ValueError("cursor belongs to a different resource")
created_at = datetime.fromisoformat(payload["t"].replace("Z", "+00:00"))
if created_at.tzinfo is None:
raise ValueError("cursor time has no timezone")
return created_at, uuid.UUID(payload["i"])
except Exception as exc:
raise ApiError(400, "invalid_request", "invalid cursor") from exc
def page_of(items: List[dict], resource: str, limit: int) -> dict:
page = items[:limit]
next_cursor = None
if len(items) > limit:
last = page[-1]
next_cursor = encode_cursor(resource, last["created_at"], last["id"])
return {"items": page, "next_cursor": next_cursor}
class Store:
def __init__(self):
self.pool: Optional[asyncpg.Pool] = None
async def open(self) -> None:
self.pool = await asyncpg.create_pool(
config.DATABASE_URL,
min_size=0,
max_size=config.DB_POOL_MAX,
timeout=config.DB_CONNECT_TIMEOUT,
command_timeout=config.DB_COMMAND_TIMEOUT,
max_inactive_connection_lifetime=60,
)
async def close(self) -> None:
if self.pool is not None:
await self.pool.close()
def acquire(self):
return self.pool.acquire(timeout=config.DB_ACQUIRE_TIMEOUT)
async def ping(self) -> bool:
async with self.acquire() as conn:
return await conn.fetchval("SELECT 1") == 1
async def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
async with self.acquire() as conn:
try:
row = await conn.fetchrow(
"""
INSERT INTO users (id, username, display_name, password_hash)
VALUES ($1, $2, $3, $4)
RETURNING id, username, display_name, created_at
""",
uuid.uuid4(), username, display_name, password_hash,
)
except asyncpg.UniqueViolationError:
raise ApiError(409, "conflict", "username already taken") from None
return user_row(row)
async def get_credentials(self, username: str) -> Optional[asyncpg.Record]:
async with self.acquire() as conn:
return await conn.fetchrow(
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
username,
)
async def create_session(self, token_hash: bytes, user_id: uuid.UUID, ttl_seconds: int) -> datetime:
async with self.acquire() as conn:
return await conn.fetchval(
"""
INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3))
RETURNING expires_at
""",
token_hash, user_id, float(ttl_seconds),
)
async def find_session(self, token_hash: bytes) -> Optional[asyncpg.Record]:
async with self.acquire() as conn:
return await conn.fetchrow(
"""
SELECT s.expires_at, u.id, u.username, u.display_name, u.created_at
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.revoked_at IS NULL AND s.expires_at > clock_timestamp()
""",
token_hash,
)
async def revoke_session(self, token_hash: bytes) -> Optional[datetime]:
async with self.acquire() as conn:
return await conn.fetchval(
"""
UPDATE sessions SET revoked_at = clock_timestamp()
WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > clock_timestamp()
RETURNING expires_at
""",
token_hash,
)
async def create_chat(self, title: str, member_ids: List[uuid.UUID]) -> dict:
chat_id = uuid.uuid4()
async with self.acquire() as conn:
try:
async with conn.transaction():
row = await conn.fetchrow(
"INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at",
chat_id, title,
)
await conn.execute(
"""
INSERT INTO chat_members (chat_id, user_id, position)
SELECT $1, m.user_id, m.ord - 1
FROM unnest($2::uuid[]) WITH ORDINALITY AS m(user_id, ord)
""",
chat_id, member_ids,
)
except asyncpg.ForeignKeyViolationError:
raise ApiError(400, "invalid_request", "unknown member in member_ids") from None
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(m) for m in member_ids],
"created_at": fmt_ts(row["created_at"]),
}
async def get_chat_for_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> Optional[dict]:
async with self.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.position) AS member_ids
FROM chats c JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = $1
AND EXISTS (SELECT 1 FROM chat_members me WHERE me.chat_id = c.id AND me.user_id = $2)
GROUP BY c.id
""",
chat_id, user_id,
)
return chat_row(row) if row else None
async def list_chats(self, user_id: uuid.UUID, limit: int, cursor: Optional[str]) -> dict:
after_t, after_i = decode_cursor("chats", cursor) if cursor else (None, None)
async with self.acquire() as conn:
rows = await conn.fetch(
"""
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.position) AS member_ids
FROM chat_members me
JOIN chats c ON c.id = me.chat_id
JOIN chat_members m ON m.chat_id = c.id
WHERE me.user_id = $1
AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $4
""",
user_id, after_t, after_i, limit + 1,
)
return page_of([chat_row(r) for r in rows], "chats", limit)
async def is_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool:
async with self.acquire() as conn:
return bool(await conn.fetchval(
"SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)",
chat_id, user_id,
))
async def create_message(
self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str, key: str, request_hash: bytes
) -> Optional[dict]:
async with self.acquire() as conn:
for _ in range(3):
try:
async with conn.transaction():
await conn.execute(
"""
DELETE FROM idempotency_keys
WHERE user_id = $1 AND chat_id = $2 AND key = $3
AND created_at < clock_timestamp() - make_interval(secs => $4)
""",
sender_id, chat_id, key, float(config.IDEMPOTENCY_TTL_SECONDS),
)
message_id = uuid.uuid4()
claimed = await conn.fetchval(
"""
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
SELECT $1, $2, $3, $4, $5
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $1)
ON CONFLICT (user_id, chat_id, key) DO NOTHING
RETURNING message_id
""",
sender_id, chat_id, key, request_hash, message_id,
)
if claimed is not None:
row = await conn.fetchrow(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES ($1, $2, $3, $4)
RETURNING id, chat_id, sender_id, text, created_at
""",
message_id, chat_id, sender_id, text,
)
return message_row(row)
except asyncpg.ForeignKeyViolationError:
return None
existing = await conn.fetchrow(
"""
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
JOIN chat_members cm ON cm.chat_id = k.chat_id AND cm.user_id = k.user_id
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3
""",
sender_id, chat_id, key,
)
if existing is None:
is_member = await conn.fetchval(
"SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)",
chat_id, sender_id,
)
if not is_member:
return None
continue
if existing["request_hash"] != request_hash:
raise ApiError(409, "conflict", "Idempotency-Key was already used with a different request")
return message_row(existing)
raise ApiError(503, "unavailable", "could not settle idempotent request, retry with the same key")
async def list_messages(self, chat_id: uuid.UUID, limit: int, cursor: Optional[str]) -> dict:
resource = str(chat_id)
async with self.acquire() as conn:
if cursor:
after_t, after_i = decode_cursor(resource, cursor)
rows = await conn.fetch(
"""
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
""",
chat_id, after_t, after_i, limit + 1,
)
else:
rows = await conn.fetch(
"""
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1
ORDER BY created_at, id
LIMIT $2
""",
chat_id, limit + 1,
)
return page_of([message_row(r) for r in rows], resource, limit)
+129
View File
@@ -0,0 +1,129 @@
name: messenger-lab3
services:
postgres:
image: postgres:17.6-alpine3.22
environment:
POSTGRES_DB: messenger
POSTGRES_USER: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets: [postgres_password]
volumes:
- pgdata:/var/lib/postgresql/data
networks: [data]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
interval: 2s
timeout: 3s
retries: 30
deploy:
resources:
limits: {cpus: "1.0", memory: 512M}
stop_grace_period: 30s
restart: unless-stopped
valkey:
image: valkey/valkey:8.1.4-alpine3.22
command: ["valkey-server", "/run/secrets/valkey_conf"]
secrets: [valkey_conf]
networks: [data]
healthcheck:
test: ["CMD-SHELL", "valkey-cli ping 2>&1 | grep -qE 'PONG|NOAUTH'"]
interval: 2s
timeout: 3s
retries: 30
deploy:
resources:
limits: {cpus: "0.25", memory: 96M}
restart: unless-stopped
migrate:
build: .
image: mtusi-messenger:lab3
command: ["python", "-m", "app.migrate"]
environment:
DATABASE_URL_FILE: /run/secrets/database_url
secrets: [database_url]
networks: [data]
depends_on:
postgres:
condition: service_healthy
deploy:
resources:
limits: {cpus: "0.25", memory: 128M}
restart: "no"
api:
build: .
image: mtusi-messenger:lab3
environment:
APP_HOST: 0.0.0.0
APP_PORT: "8080"
APP_ENV: ${APP_ENV:-lab}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
SESSION_STORE: postgres
SESSION_CACHE_MAX_SECONDS: ${SESSION_CACHE_MAX_SECONDS:-300}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
DATABASE_URL_FILE: /run/secrets/database_url
CACHE_URL_FILE: /run/secrets/cache_url
DB_POOL_MAX: ${DB_POOL_MAX:-10}
secrets: [database_url, cache_url]
networks: [edge, data]
depends_on:
postgres:
condition: service_healthy
valkey:
condition: service_healthy
migrate:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status==200 else 1)"]
interval: 5s
timeout: 3s
start_period: 5s
retries: 3
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits: {cpus: "0.5", memory: 256M}
stop_signal: SIGTERM
stop_grace_period: 10s
restart: unless-stopped
lb:
image: haproxy:3.2.4-alpine
volumes:
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
ports:
- "127.0.0.1:${APP_PORT:-8080}:8080"
networks: [edge]
depends_on:
api:
condition: service_started
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8405/lb-health"]
interval: 5s
timeout: 2s
retries: 3
deploy:
resources:
limits: {cpus: "0.5", memory: 128M}
restart: unless-stopped
networks:
edge: {}
data:
internal: true
volumes:
pgdata:
secrets:
postgres_password:
file: ./secrets/postgres_password
database_url:
file: ./secrets/database_url
cache_url:
file: ./secrets/cache_url
valkey_conf:
file: ./secrets/valkey.conf
+151
View File
@@ -0,0 +1,151 @@
{
"profile": "closed loop, 8 workers, each: POST message (retry same key) + GET history; client timeout 2 s",
"action": "scripts/stop-container.sh messenger-lab3-api-1",
"action_started_s": 5.01,
"action_finished_s": 5.85,
"action_returncode": 0,
"action_output": [
"2026-10-15T11:50:36Z stopped messenger-lab3-api-1 instance=api-44e6d584 state=exited"
],
"elapsed_s": 25.01,
"requests": 15020,
"successful": 15020,
"errors": 0,
"error_ratio": 0.0,
"successful_rps": 600.5,
"latency_ms_success": {
"p50": 7.9,
"p95": 45.1,
"p99": 59.3,
"max": 1019.3
},
"slow_over_500ms_after_action": 16,
"error_window_s": null,
"recovery_s_after_action": 2.72,
"instances_before": {
"api-44e6d584": 2031,
"api-183aa91a": 2034
},
"instances_last_5s": {
"api-183aa91a": 2848
},
"timeline_ok_err_per_s": {
"0": [
702,
0
],
"1": [
658,
0
],
"2": [
872,
0
],
"3": [
933,
0
],
"4": [
887,
0
],
"5": [
436,
0
],
"6": [
13,
0
],
"7": [
196,
0
],
"8": [
679,
0
],
"9": [
639,
0
],
"10": [
581,
0
],
"11": [
687,
0
],
"12": [
616,
0
],
"13": [
582,
0
],
"14": [
644,
0
],
"15": [
574,
0
],
"16": [
655,
0
],
"17": [
619,
0
],
"18": [
536,
0
],
"19": [
653,
0
],
"20": [
634,
0
],
"21": [
463,
0
],
"22": [
618,
0
],
"23": [
655,
0
],
"24": [
484,
0
],
"25": [
4,
0
]
},
"docker_stats_mid": [
"messenger-lab3-api-2\t50.73%\t86.94MiB / 256MiB",
"messenger-lab3-lb-1\t13.03%\t15.18MiB / 128MiB",
"messenger-lab3-postgres-1\t21.00%\t49.02MiB / 512MiB",
"messenger-lab3-valkey-1\t1.77%\t10.82MiB / 96MiB"
],
"integrity": {
"stored_messages": 7510,
"confirmed_writes": 7510,
"duplicate_ids": 0,
"duplicate_texts": 0,
"confirmed_missing": 0
}
}
+151
View File
@@ -0,0 +1,151 @@
{
"profile": "closed loop, 8 workers, each: POST message (retry same key) + GET history; client timeout 2 s",
"action": "scripts/stop-container.sh messenger-lab3-api-2",
"action_started_s": 5.02,
"action_finished_s": 5.63,
"action_returncode": 0,
"action_output": [
"2026-10-15T11:51:13Z stopped messenger-lab3-api-2 instance=api-183aa91a state=exited"
],
"elapsed_s": 25.01,
"requests": 15264,
"successful": 15264,
"errors": 0,
"error_ratio": 0.0,
"successful_rps": 610.3,
"latency_ms_success": {
"p50": 8.1,
"p95": 43.8,
"p99": 57.5,
"max": 1019.9
},
"slow_over_500ms_after_action": 16,
"error_window_s": null,
"recovery_s_after_action": 2.52,
"instances_before": {
"api-183aa91a": 2312,
"api-85c04c87": 2313
},
"instances_last_5s": {
"api-85c04c87": 2967
},
"timeline_ok_err_per_s": {
"0": [
863,
0
],
"1": [
1010,
0
],
"2": [
963,
0
],
"3": [
999,
0
],
"4": [
766,
0
],
"5": [
305,
0
],
"6": [
14,
0
],
"7": [
277,
0
],
"8": [
658,
0
],
"9": [
575,
0
],
"10": [
524,
0
],
"11": [
650,
0
],
"12": [
584,
0
],
"13": [
646,
0
],
"14": [
571,
0
],
"15": [
580,
0
],
"16": [
544,
0
],
"17": [
634,
0
],
"18": [
623,
0
],
"19": [
502,
0
],
"20": [
562,
0
],
"21": [
641,
0
],
"22": [
494,
0
],
"23": [
623,
0
],
"24": [
651,
0
],
"25": [
5,
0
]
},
"docker_stats_mid": [
"messenger-lab3-api-1\t51.61%\t86.96MiB / 256MiB",
"messenger-lab3-lb-1\t14.03%\t15.85MiB / 128MiB",
"messenger-lab3-postgres-1\t30.28%\t47.1MiB / 512MiB",
"messenger-lab3-valkey-1\t1.79%\t10.82MiB / 96MiB"
],
"integrity": {
"stored_messages": 7632,
"confirmed_writes": 7632,
"duplicate_ids": 0,
"duplicate_texts": 0,
"confirmed_missing": 0
}
}
+90
View File
@@ -0,0 +1,90 @@
=== round 1 2026-10-15T11:45:37Z
NAME STATUS
messenger-lab3-api-1 Up 40 seconds (healthy)
messenger-lab3-api-2 Up 40 seconds (healthy)
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8088"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 110, "failed_attempts": 0, "first_recovery_seconds": 3.411}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
--- after hook:
2026-10-15T11:45:41Z stopped messenger-lab3-api-2 (2179542de855) instance=api-6a5e985e state=exited
NAME STATUS
messenger-lab3-api-1 Up 57 seconds (healthy)
messenger-lab3-api-2 Exited (0) 14 seconds ago
--- restore:
NAME STATUS
messenger-lab3-api-1 Up About a minute (healthy)
messenger-lab3-api-2 Up 5 seconds (healthy)
=== round 2 2026-10-15T11:46:05Z
NAME STATUS
messenger-lab3-api-1 Up About a minute (healthy)
messenger-lab3-api-2 Up 8 seconds (healthy)
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8088"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 112, "failed_attempts": 0, "first_recovery_seconds": 2.682}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
--- after hook:
2026-10-15T11:46:07Z stopped messenger-lab3-api-2 (2179542de855) instance=api-60495ffd state=exited
NAME STATUS
messenger-lab3-api-1 Up About a minute (healthy)
messenger-lab3-api-2 Exited (0) 14 seconds ago
--- restore:
NAME STATUS
messenger-lab3-api-1 Up About a minute (healthy)
messenger-lab3-api-2 Up 5 seconds (healthy)
=== round 3 2026-10-15T11:46:43Z
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8088"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 116, "failed_attempts": 0, "first_recovery_seconds": 3.031}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
--- after hook:
2026-10-15T11:46:46Z stopped messenger-lab3-api-2 (2179542de855) instance=api-ddb0f40b state=exited
NAME STATUS
messenger-lab3-api-1 Up 2 minutes (healthy)
messenger-lab3-api-2 Exited (0) 14 seconds ago
--- restore:
NAME STATUS
messenger-lab3-api-1 Up 2 minutes (healthy)
messenger-lab3-api-2 Up 5 seconds (healthy)
=== round 4 2026-10-15T11:47:11Z
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8088"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 123, "failed_attempts": 0, "first_recovery_seconds": 1.565}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
--- after hook:
2026-10-15T11:47:14Z stopped messenger-lab3-api-2 (2179542de855) instance=api-a0e07848 state=exited
NAME STATUS
messenger-lab3-api-1 Up 2 minutes (healthy)
messenger-lab3-api-2 Exited (0) 14 seconds ago
--- restore:
NAME STATUS
messenger-lab3-api-1 Up 2 minutes (healthy)
messenger-lab3-api-2 Up 5 seconds (healthy)
=== round 5 2026-10-15T11:47:38Z
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8088"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 111, "failed_attempts": 0, "first_recovery_seconds": 2.691}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
--- after hook:
2026-10-15T11:47:42Z stopped messenger-lab3-api-2 (2179542de855) instance=api-1968c7c7 state=exited
NAME STATUS
messenger-lab3-api-1 Up 2 minutes (healthy)
messenger-lab3-api-2 Exited (0) 14 seconds ago
--- restore:
NAME STATUS
messenger-lab3-api-1 Up 3 minutes (healthy)
messenger-lab3-api-2 Up 5 seconds (healthy)
=== round 6 (one extra LB request first to shift round-robin parity) 2026-10-15T11:48:18Z
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8088"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 114, "failed_attempts": 0, "first_recovery_seconds": 2.913}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
--- after hook:
2026-10-15T11:48:21Z stopped messenger-lab3-api-1 (d58678cd6981) instance=api-2afcbc6e state=exited
NAME STATUS
messenger-lab3-api-1 Exited (0) 14 seconds ago
messenger-lab3-api-2 Up 37 seconds (healthy)
--- restore:
NAME STATUS
messenger-lab3-api-1 Up 5 seconds (healthy)
messenger-lab3-api-2 Up 44 seconds (healthy)
+11
View File
@@ -0,0 +1,11 @@
ok - round 1: 32 parallel requests, 1 message, replicas {'api-44e6d584': 16, 'api-183aa91a': 16}
ok - round 2: 32 parallel requests, 1 message, replicas {'api-183aa91a': 16, 'api-44e6d584': 16}
ok - round 3: 32 parallel requests, 1 message, replicas {'api-44e6d584': 16, 'api-183aa91a': 16}
ok - round 4: 32 parallel requests, 1 message, replicas {'api-183aa91a': 16, 'api-44e6d584': 16}
ok - round 5: 32 parallel requests, 1 message, replicas {'api-183aa91a': 16, 'api-44e6d584': 16}
ok - different body with same key -> 409, original replays unchanged
ok - same key independent per user and per chat
ok - missing/invalid Idempotency-Key -> 400, max-length key accepted
ok - replay needs a valid session and chat access (404 outsider, 401 revoked)
ok - DB rows in chat: 8, history items: 8, no duplicate texts
PASS: shared idempotency
+11
View File
@@ -0,0 +1,11 @@
# all API replicas stopped -> LB answers itself
Container messenger-lab3-api-4 Stopped
HTTP/1.1 503 Service Unavailable
x-request-id: 288cf625-3642-4f98-90c3-5685c8d020f5
content-type: application/json
{"error":{"code":"unavailable","message":"no healthy API replica","request_id":"288cf625-3642-4f98-90c3-5685c8d020f5"}}
NAME STATUS
messenger-lab3-api-3 Up 5 seconds (healthy)
messenger-lab3-api-4 Up 5 seconds (healthy)
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 3,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.019,
"concurrency": 4,
"successful_requests": 25240,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 840.8,
"successful_latency_ms": {
"p50": 4.39,
"p95": 6.434,
"p99": 10.283
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+31
View File
@@ -0,0 +1,31 @@
=== 2026-10-15T11:48:52Z before
NAME STATUS CREATED AT
messenger-lab3-api-1 Up 15 seconds (healthy) 2026-10-15 14:44:55 +0300 MSK
messenger-lab3-api-2 Up 54 seconds (healthy) 2026-10-15 14:44:55 +0300 MSK
messenger-lab3-lb-1 Up 3 minutes (healthy) 2026-10-15 14:44:55 +0300 MSK
messenger-lab3-migrate-1 Exited (0) 15 seconds ago 2026-10-15 14:44:55 +0300 MSK
messenger-lab3-postgres-1 Up 4 minutes (healthy) 2026-10-15 14:44:00 +0300 MSK
messenger-lab3-valkey-1 Up 4 minutes (healthy) 2026-10-15 14:44:00 +0300 MSK
/messenger-lab3-api-1 started=2026-10-15T11:48:37.123716387Z
/messenger-lab3-api-2 started=2026-10-15T11:47:58.013947425Z
/messenger-lab3-lb-1 started=2026-10-15T11:44:57.43671605Z
/messenger-lab3-postgres-1 started=2026-10-15T11:44:00.488171093Z
/messenger-lab3-valkey-1 started=2026-10-15T11:44:00.486537093Z
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8088"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
=== after
NAME STATUS
messenger-lab3-api-1 Up 5 seconds (healthy)
messenger-lab3-api-2 Up 5 seconds (healthy)
messenger-lab3-lb-1 Up 5 seconds (healthy)
messenger-lab3-migrate-1 Exited (0) 6 seconds ago
messenger-lab3-postgres-1 Up 9 seconds (healthy)
messenger-lab3-valkey-1 Up 9 seconds (healthy)
/messenger-lab3-api-1 started=2026-10-15T11:48:59.064957134Z
/messenger-lab3-api-2 started=2026-10-15T11:48:58.9953378Z
/messenger-lab3-lb-1 started=2026-10-15T11:48:59.147870509Z
/messenger-lab3-postgres-1 started=2026-10-15T11:48:55.83871384Z
/messenger-lab3-valkey-1 started=2026-10-15T11:48:55.838344632Z
DRIVER VOLUME NAME
local messenger-lab3_pgdata
+259
View File
@@ -0,0 +1,259 @@
{
"profile": "closed loop, 8 workers, each: POST message (retry same key) + GET history; client timeout 2 s",
"action": "scripts/rolling-update.sh",
"action_started_s": 5.02,
"action_finished_s": 23.01,
"action_returncode": 0,
"action_output": [
"#13 DONE 0.0s",
"11:52:12 new /messenger-lab3-api-3 healthy; stopping old /messenger-lab3-api-1",
"11:52:20 new /messenger-lab3-api-4 healthy; stopping old /messenger-lab3-api-2",
"NAME IMAGE STATUS",
"messenger-lab3-api-3 mtusi-messenger:lab3 Up 16 seconds (healthy)",
"messenger-lab3-api-4 mtusi-messenger:lab3 Up 8 seconds (healthy)"
],
"elapsed_s": 50.01,
"requests": 41154,
"successful": 41154,
"errors": 0,
"error_ratio": 0.0,
"successful_rps": 822.9,
"latency_ms_success": {
"p50": 7.4,
"p95": 16.3,
"p99": 53.7,
"max": 1022.8
},
"slow_over_500ms_after_action": 24,
"error_window_s": null,
"recovery_s_after_action": 19.86,
"instances_before": {
"api-85c04c87": 2165,
"api-e53b9e96": 2165
},
"instances_last_5s": {
"api-57303f43": 1991,
"api-aef30e7d": 1991
},
"timeline_ok_err_per_s": {
"0": [
688,
0
],
"1": [
790,
0
],
"2": [
968,
0
],
"3": [
976,
0
],
"4": [
889,
0
],
"5": [
693,
0
],
"6": [
592,
0
],
"7": [
754,
0
],
"8": [
1146,
0
],
"9": [
1063,
0
],
"10": [
841,
0
],
"11": [
848,
0
],
"12": [
907,
0
],
"13": [
1028,
0
],
"14": [
473,
0
],
"15": [
274,
0
],
"16": [
953,
0
],
"17": [
877,
0
],
"18": [
898,
0
],
"19": [
917,
0
],
"20": [
1006,
0
],
"21": [
988,
0
],
"22": [
627,
0
],
"23": [
22,
0
],
"24": [
153,
0
],
"25": [
901,
0
],
"26": [
935,
0
],
"27": [
861,
0
],
"28": [
924,
0
],
"29": [
987,
0
],
"30": [
707,
0
],
"31": [
1004,
0
],
"32": [
906,
0
],
"33": [
829,
0
],
"34": [
911,
0
],
"35": [
881,
0
],
"36": [
883,
0
],
"37": [
914,
0
],
"38": [
818,
0
],
"39": [
925,
0
],
"40": [
751,
0
],
"41": [
1027,
0
],
"42": [
869,
0
],
"43": [
823,
0
],
"44": [
937,
0
],
"45": [
790,
0
],
"46": [
820,
0
],
"47": [
801,
0
],
"48": [
885,
0
],
"49": [
690,
0
],
"50": [
4,
0
]
},
"docker_stats_mid": [
"messenger-lab3-api-1\t51.08%\t175.1MiB / 256MiB",
"messenger-lab3-api-2\t50.01%\t82.92MiB / 256MiB",
"messenger-lab3-api-3\t49.31%\t50.11MiB / 256MiB",
"messenger-lab3-lb-1\t32.61%\t16.47MiB / 128MiB",
"messenger-lab3-postgres-1\t52.87%\t92.39MiB / 512MiB",
"messenger-lab3-valkey-1\t4.29%\t10.84MiB / 96MiB"
],
"integrity": {
"stored_messages": 20577,
"confirmed_writes": 20577,
"duplicate_ids": 0,
"duplicate_texts": 0,
"confirmed_missing": 0
}
}
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://localhost:8088"
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
+10
View File
@@ -0,0 +1,10 @@
2026-10-15T11:45:41Z stopped messenger-lab3-api-2 (2179542de855) instance=api-6a5e985e state=exited
2026-10-15T11:46:07Z stopped messenger-lab3-api-2 (2179542de855) instance=api-60495ffd state=exited
2026-10-15T11:46:46Z stopped messenger-lab3-api-2 (2179542de855) instance=api-ddb0f40b state=exited
2026-10-15T11:47:14Z stopped messenger-lab3-api-2 (2179542de855) instance=api-a0e07848 state=exited
2026-10-15T11:47:42Z stopped messenger-lab3-api-2 (2179542de855) instance=api-1968c7c7 state=exited
2026-10-15T11:48:21Z stopped messenger-lab3-api-1 (d58678cd6981) instance=api-2afcbc6e state=exited
2026-10-15T11:50:36Z stopped messenger-lab3-api-1 instance=api-44e6d584 state=exited
2026-10-15T11:51:13Z stopped messenger-lab3-api-2 instance=api-183aa91a state=exited
2026-10-15T12:01:37Z stopped messenger-lab3-api-1 (698dc5937ee2) instance=api-3bacb399 state=exited
2026-10-15T12:02:02Z stopped messenger-lab3-api-1 instance=api-8dd03a25 state=exited
+49
View File
@@ -0,0 +1,49 @@
# 2026-10-15T11:54:10Z one session (one Bearer token, single login) served by different replicas via LB
1 200 X-Instance-Id=api-255e07d5 user=u_demo_b7ea3c6d31d8
2 200 X-Instance-Id=api-624de536 user=u_demo_b7ea3c6d31d8
3 200 X-Instance-Id=api-255e07d5 user=u_demo_b7ea3c6d31d8
4 200 X-Instance-Id=api-624de536 user=u_demo_b7ea3c6d31d8
5 200 X-Instance-Id=api-255e07d5 user=u_demo_b7ea3c6d31d8
6 200 X-Instance-Id=api-624de536 user=u_demo_b7ea3c6d31d8
# instance id -> container mapping (alias file inside each container)
/messenger-lab3-api-3 api-624de536
/messenger-lab3-api-4 api-255e07d5
# published ports: only lb
NAME PORTS
messenger-lab3-api-3 8080/tcp
messenger-lab3-api-4 8080/tcp
messenger-lab3-lb-1 127.0.0.1:8088->8080/tcp
messenger-lab3-postgres-1
messenger-lab3-valkey-1
# limits (NanoCpus, Memory bytes)
/messenger-lab3-api-3 cpus=500000000 mem=268435456
/messenger-lab3-api-4 cpus=500000000 mem=268435456
/messenger-lab3-lb-1 cpus=500000000 mem=134217728
/messenger-lab3-postgres-1 cpus=1000000000 mem=536870912
/messenger-lab3-valkey-1 cpus=250000000 mem=100663296
# images
CONTAINER REPOSITORY TAG IMAGE ID SIZE
messenger-lab3-api-3 mtusi-messenger lab3 ae4ccc72928e 221MB
messenger-lab3-api-4 mtusi-messenger lab3 ae4ccc72928e 221MB
messenger-lab3-lb-1 haproxy 3.2.4-alpine 5b478a21578f 32.8MB
messenger-lab3-migrate-1 mtusi-messenger lab3 ae4ccc72928e 221MB
messenger-lab3-postgres-1 postgres 17.6-alpine3.22 29e645e20571 270MB
messenger-lab3-valkey-1 valkey/valkey 8.1.4-alpine3.22 b9cc2f089926 47.6MB
# migrations: applied once by the one-shot migrate service
INFO migrate: migrations up to date: 0 applied now, 2 before
INFO migrate: migrations up to date: 0 applied now, 2 before
INFO migrate: migrations up to date: 0 applied now, 2 before
version | applied_at
------------------+-------------------------------
0001_init | 2026-10-15 11:44:03.489347+00
0002_idempotency | 2026-10-15 11:44:03.497728+00
(2 rows)
# direct access to postgres from host / lb is impossible (internal network):
nc: bad address 'postgres'
postgres unreachable from lb
+51
View File
@@ -0,0 +1,51 @@
global
log stdout format raw local0 info
maxconn 2048
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold other 2s
hold refused 2s
hold nx 2s
hold timeout 2s
hold obsolete 2s
accepted_payload_size 8192
defaults
mode http
log global
option httplog
option dontlognull
timeout connect 1s
timeout client 30s
timeout server 10s
timeout http-request 10s
timeout queue 5s
timeout check 1s
retries 3
option redispatch 1
retry-on conn-failure empty-response
unique-id-format %[uuid()]
http-error status 502 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API replica failed\",\"request_id\":\"%[unique-id]\"}}"
http-error status 503 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"no healthy API replica\",\"request_id\":\"%[unique-id]\"}}"
http-error status 504 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API replica timeout\",\"request_id\":\"%[unique-id]\"}}"
frontend public
bind :8080
default_backend api
frontend monitor
bind 127.0.0.1:8405
monitor-uri /lb-health
backend api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host lb
http-check expect status 200
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
server-template api 8 api:8080
+49
View File
@@ -0,0 +1,49 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len 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_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
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)
);
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT messages_sender_member_fk FOREIGN KEY (chat_id, sender_id)
REFERENCES chat_members (chat_id, user_id),
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
);
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL,
revoked_at timestamptz
);
CREATE INDEX sessions_expires_idx ON sessions (expires_at);
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE idempotency_keys (
user_id uuid NOT NULL REFERENCES users (id),
chat_id uuid NOT NULL REFERENCES chats (id),
key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid NOT NULL REFERENCES messages (id) DEFERRABLE INITIALLY DEFERRED,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, chat_id, key),
CONSTRAINT idempotency_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$')
);
CREATE INDEX idempotency_keys_created_idx ON idempotency_keys (created_at);
+6
View File
@@ -0,0 +1,6 @@
fastapi==0.142.2
uvicorn[standard]==0.54.0
pydantic==2.13.5
asyncpg==0.32.0
redis==8.1.0
argon2-cffi==25.1.0
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mkdir -p secrets
gen() { python3 -c 'import secrets; print(secrets.token_hex(24))'; }
if [ ! -f secrets/postgres_password ]; then
gen > secrets/postgres_password
echo "created secrets/postgres_password"
fi
PG_PASS=$(cat secrets/postgres_password)
printf 'postgresql://messenger:%s@postgres:5432/messenger\n' "$PG_PASS" > secrets/database_url
if [ ! -f secrets/valkey.conf ]; then
{
printf 'requirepass %s\n' "$(gen)"
printf 'save ""\nappendonly no\n'
printf 'maxmemory 64mb\nmaxmemory-policy volatile-lru\n'
} > secrets/valkey.conf
echo "created secrets/valkey.conf"
fi
VK_PASS=$(sed -n 's/^requirepass //p' secrets/valkey.conf)
printf 'redis://:%s@valkey:6379/0\n' "$VK_PASS" > secrets/cache_url
chmod 644 secrets/*
echo "secrets ready in ./secrets (not tracked by git)"
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose ps --format 'table {{.Name}}\t{{.Status}}'
docker compose stop lb api
docker compose stop valkey postgres
docker compose up -d --no-build --wait api lb
docker compose ps --format 'table {{.Name}}\t{{.Status}}'
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose up -d --no-build --no-recreate --wait api
docker compose ps api --format 'table {{.Name}}\t{{.Status}}'
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
N=$(docker compose ps -q api | wc -l | tr -d ' ')
[ "$N" -ge 1 ] || { echo "api is not running" >&2; exit 1; }
OLD=$(docker compose ps -q api)
docker compose build api
docker compose run --rm --no-deps migrate
wait_healthy() {
i=0
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$1")" = healthy ]; do
i=$((i + 1)); [ "$i" -le 60 ] || { echo "replica $1 not healthy" >&2; exit 1; }
sleep 1
done
}
for old in $OLD; do
before=$(docker compose ps -q api | sort)
docker compose up -d --no-deps --no-recreate --scale api=$((N + 1)) api >/dev/null 2>&1
new=$(docker compose ps -q api | sort | grep -vxF "$before" || true)
[ -n "$new" ] || { echo "no new replica started" >&2; exit 1; }
wait_healthy "$new"
sleep 2
printf '%s new %s healthy; stopping old %s\n' "$(date -u +%H:%M:%S)" \
"$(docker inspect -f '{{.Name}}' "$new")" "$(docker inspect -f '{{.Name}}' "$old")"
docker stop --time 8 "$old" >/dev/null
docker rm "$old" >/dev/null
done
docker compose ps api --format 'table {{.Name}}\t{{.Image}}\t{{.Status}}'
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
name=${1:?usage: stop-container.sh <project>-api-N}
case "$name" in *-api-*) ;; *) echo "refusing: $name is not an API replica" >&2; exit 2;; esac
alias=$(docker exec "$name" cat /tmp/instance-id 2>/dev/null || echo "?")
docker stop --time 8 "$name" >/dev/null
printf '%s stopped %s instance=%s state=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$name" "$alias" \
"$(docker inspect -f '{{.State.Status}}' "$name")" | tee -a evidence/stop-one.txt
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
log=evidence/stop-one.txt
for cid in $(docker compose ps -q api); do
alias=$(docker exec "$cid" cat /tmp/instance-id 2>/dev/null || true)
if [ "$alias" = "$TARGET_INSTANCE_ID" ]; then
name=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##')
docker stop --time 8 "$cid" >/dev/null
state=$(docker inspect -f '{{.State.Status}}' "$cid")
printf '%s stopped %s (%s) instance=%s state=%s\n' \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$name" "$(printf %.12s "$cid")" "$alias" "$state" | tee -a "$log"
exit 0
fi
done
echo "no running api container reports instance id $TARGET_INSTANCE_ID" >&2
exit 1
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
import json
import math
import shlex
import subprocess
import sys
import threading
import time
import uuid
from collections import Counter, defaultdict
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run
def pct(values, p):
return round(1000 * values[max(0, math.ceil(p * len(values)) - 1)], 1) if values else None
def docker_stats():
ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split()
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}", *ids],
capture_output=True, text=True)
return sorted(out.stdout.splitlines())
def main():
def configure(p):
p.add_argument("--duration", type=float, default=25)
p.add_argument("--concurrency", type=int, default=8)
p.add_argument("--action", default=None, help="command run once at --action-at seconds")
p.add_argument("--action-at", type=float, default=5)
p.add_argument("--output", default=None)
args = arguments("Load with an operator action in the middle", configure)
boot = Client(args.base_url, timeout=10)
alice, bob, _eve, chat = boot.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/messages"
events = []
confirmed = []
lock = threading.Lock()
t0 = time.monotonic()
stop_at = t0 + args.duration
action_info = {}
def worker(wid):
c = Client(args.base_url, timeout=2)
key, text, n = None, None, 0
while time.monotonic() < stop_at:
if key is None:
key = uuid.uuid4().hex
text = "chaos-%d-%d-%s" % (wid, n, key[:8])
for kind in ("write", "read"):
start = time.monotonic()
try:
if kind == "write":
r = c.call("POST", path, 201, actor=alice, body={"text": text}, headers={"Idempotency-Key": key}, schema="Message")
else:
r = c.call("GET", path + "?limit=20", actor=bob, schema="MessagePage")
ok, inst = True, r["headers"].get("X-Instance-Id")
except Failure:
ok, inst = False, None
end = time.monotonic()
with lock:
events.append((start - t0, kind, ok, end - start, inst))
if ok and kind == "write":
confirmed.append(r["json"])
if kind == "write" and ok:
key, n = None, n + 1
if not ok:
time.sleep(0.05)
def action():
time.sleep(args.action_at)
action_info["started"] = time.monotonic() - t0
proc = subprocess.run(shlex.split(args.action), cwd=ROOT, capture_output=True, text=True)
action_info["finished"] = time.monotonic() - t0
action_info["returncode"] = proc.returncode
action_info["output_tail"] = proc.stdout.strip().splitlines()[-6:]
stats_mid = []
threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)]
if args.action:
threads.append(threading.Thread(target=action))
for t in threads:
t.start()
time.sleep(min(args.duration / 2, args.action_at + 3))
stats_mid = docker_stats()
for t in threads:
t.join()
elapsed = time.monotonic() - t0
ok_lat = sorted(e[3] for e in events if e[2])
errors = [e for e in events if not e[2]]
a0 = action_info.get("started")
timeline = defaultdict(lambda: [0, 0])
for e in events:
timeline[int(e[0])][0 if e[2] else 1] += 1
report = {
"profile": "closed loop, %d workers, each: POST message (retry same key) + GET history; client timeout 2 s" % args.concurrency,
"action": args.action, "action_started_s": a0 and round(a0, 2), "action_finished_s": action_info.get("finished") and round(action_info["finished"], 2),
"action_returncode": action_info.get("returncode"), "action_output": action_info.get("output_tail"),
"elapsed_s": round(elapsed, 2), "requests": len(events), "successful": len(ok_lat), "errors": len(errors),
"error_ratio": round(len(errors) / len(events), 5) if events else None,
"successful_rps": round(len(ok_lat) / elapsed, 1),
"latency_ms_success": {"p50": pct(ok_lat, .50), "p95": pct(ok_lat, .95), "p99": pct(ok_lat, .99), "max": pct(ok_lat, 1)},
"slow_over_500ms_after_action": sum(1 for e in events if e[2] and e[3] > .5 and a0 is not None and e[0] >= a0),
"error_window_s": [round(errors[0][0] - (a0 or 0), 2), round(max(e[0] + e[3] for e in errors) - (a0 or 0), 2)] if errors else None,
"recovery_s_after_action": None,
"instances_before": dict(Counter(e[4] for e in events if e[2] and (a0 is None or e[0] < a0))),
"instances_last_5s": dict(Counter(e[4] for e in events if e[2] and e[0] > elapsed - 5)),
"timeline_ok_err_per_s": {k: v for k, v in sorted(timeline.items())},
"docker_stats_mid": stats_mid,
}
if a0 is not None:
bad_ends = [e[0] + e[3] for e in events if e[0] + e[3] >= a0 and (not e[2] or e[3] > 1)]
report["recovery_s_after_action"] = round(max(bad_ends) - a0, 2) if bad_ends else 0.0
items, cursor = [], None
while True:
q = path + "?limit=100" + ("&cursor=" + quote(cursor, safe="") if cursor else "")
page = boot.call("GET", q, actor=bob, schema="MessagePage")["json"]
items += page["items"]
cursor = page["next_cursor"]
if cursor is None:
break
ids = Counter(m["id"] for m in items)
texts = Counter(m["text"] for m in items)
stored = {m["id"]: m for m in items}
report["integrity"] = {
"stored_messages": len(items), "confirmed_writes": len(confirmed),
"duplicate_ids": sum(1 for n in ids.values() if n > 1), "duplicate_texts": sum(1 for n in texts.values() if n > 1),
"confirmed_missing": sum(1 for m in confirmed if stored.get(m["id"]) != m),
}
text = json.dumps(report, ensure_ascii=False, indent=1)
print(text)
if args.output:
Path(args.output).write_text(text + "\n")
check(report["integrity"]["duplicate_texts"] == 0 and report["integrity"]["confirmed_missing"] == 0, "data integrity violated")
check(action_info.get("returncode", 0) == 0, "action failed")
if __name__ == "__main__":
run(main)
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
import subprocess
import sys
import threading
import uuid
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run
def post(c, actor, chat, text, key, expected=201):
return c.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", expected, actor=actor,
body={"text": text}, headers={"Idempotency-Key": key},
schema="Message" if expected == 201 else None)
def history(c, actor, chat):
return c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=actor, schema="MessagePage")["json"]["items"]
def db_count(chat_id):
sql = "SELECT count(*) FROM messages WHERE chat_id = '%s'" % uuid.UUID(chat_id)
out = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAX", "-c", sql],
cwd=ROOT, capture_output=True, text=True)
return int(out.stdout.strip()) if out.returncode == 0 else None
def main():
def configure(p):
p.add_argument("--parallel", type=int, default=32)
p.add_argument("--rounds", type=int, default=5)
args = arguments("Concurrent idempotency through the LB", configure)
c = Client(args.base_url, timeout=10)
alice, bob, eve, chat = c.bootstrap()
for rnd in range(args.rounds):
key = "par-%d-%s" % (rnd, uuid.uuid4().hex)
text = "одновременно " + key
barrier = threading.Barrier(args.parallel)
results, errors = [], []
def worker():
local = Client(args.base_url, timeout=10)
barrier.wait()
try:
r = post(local, alice, chat, text, key)
results.append((r["json"], r["headers"]["X-Instance-Id"]))
except Failure as exc:
errors.append(str(exc))
threads = [threading.Thread(target=worker) for _ in range(args.parallel)]
for t in threads:
t.start()
for t in threads:
t.join()
check(not errors, "concurrent replay failed: %s" % errors[:3])
ids = {m["id"] for m, _ in results}
instances = Counter(i for _, i in results)
check(len(ids) == 1, "concurrent requests created %d messages" % len(ids))
check(all(m == results[0][0] for m, _ in results), "replays returned different bodies")
check(len(instances) >= 2, "all requests hit one replica; LB not balancing")
stored = [m for m in history(c, bob, chat) if m["text"] == text]
check(len(stored) == 1, "history has %d copies" % len(stored))
print("ok - round %d: %d parallel requests, 1 message, replicas %s" % (rnd + 1, args.parallel, dict(instances)))
key = uuid.uuid4().hex
first = post(c, alice, chat, "оригинал", key)["json"]
for _ in range(4):
post(c, alice, chat, "другой текст", key, expected=409)
check(post(c, alice, chat, "оригинал", key)["json"] == first, "replay changed")
print("ok - different body with same key -> 409, original replays unchanged")
other = post(c, bob, chat, "оригинал", key)["json"]
check(other["id"] != first["id"] and other["sender_id"] == bob["id"], "key leaked across users")
chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "второй", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
third = post(c, alice, chat2, "оригинал", key)["json"]
check(third["id"] != first["id"] and third["chat_id"] == chat2["id"], "key leaked across chats")
print("ok - same key independent per user and per chat")
for bad in ("", "with space", "кириллица", "x" * 129, "a/b"):
try:
post(c, alice, chat, "bad key", bad, expected=400)
except UnicodeEncodeError:
pass
c.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400, actor=alice, body={"text": "без ключа"})
post(c, alice, chat, "ok", "A-Za-z0-9._:-" + "k" * 115)
print("ok - missing/invalid Idempotency-Key -> 400, max-length key accepted")
post(c, eve, chat, "оригинал", key, expected=404)
sid = Client(args.base_url)
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=bob)
post(sid, bob, chat, "оригинал", key, expected=401)
print("ok - replay needs a valid session and chat access (404 outsider, 401 revoked)")
count = db_count(chat["id"])
texts = Counter(m["text"] for m in history(c, alice, chat))
check(all(n == 1 for t, n in texts.items() if t.startswith("одновременно")), "duplicates in history")
print("ok - DB rows in chat: %s, history items: %d, no duplicate texts" % (count, sum(texts.values())))
print("PASS: shared idempotency")
if __name__ == "__main__":
run(main)