ЛР 3 — БВТ2304 — ivanstorozhev — на 4

Две реплики API за HAProxy делят PostgreSQL и сессии, поэтому остановка одной не рвёт чтение и запись. Idempotency-Key не даёт повторной отправке создать второе сообщение.

Автор / группа: ivanstorozhev, БВТ2304
Целевая оценка (3/4/5): 4
Трек 5, если заявлен: не заявлен

Что реализовано и что перенесено: из lab2 перенесён Spring Boot API. PostgreSQL хранит пользователей, чаты, участников, сообщения, сессии и ключи идемпотентности. Redis только кэширует разбор Bearer и обходится при отказе. Пароли — Argon2id. Миграции Liquibase запускает одноразовый сервис migrate, реплики API схему сами не накатывают. Добавлены HAProxy без sticky session, две реплики, X-Instance-Id, обязательный Idempotency-Key, scripts/stop-one.sh, scripts/restart.sh и scripts/rolling-update.sh. Время в ответах пишется с шестью знаками дробной секунды, чтобы его принимал Python 3.9.

Команды запуска из чистого clone:
cp .env.example .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build
curl -fsS http://127.0.0.1:8080/health/ready
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
docker compose --env-file .env start api

Результаты проверок и ссылка на REPORT.md: подробности и числа в REPORT.md
make check — PASS: offline skeleton structure, local refs and Python syntax.
make test — PASS: lab3 public API scenario (Python 3.9.6).
make test-persistence ACTION_SCRIPT=scripts/restart.sh — PASS: persistence preserved confirmed data and existing session.
make test-failover ACTION_SCRIPT=scripts/stop-one.sh — PASS: две реплики до отказа, восстановление записи за 1.16 с, 114 успешных записей и 2 ошибки перехода.
mvn -q test в backend/ — 13 тестов без ошибок, включая повтор ключа, 409 на другое тело и 8 параллельных запросов с одним ключом. После фикса формата времени заново прогнан ApiIntegrationTest и публичный make test.

Ограничения / известные ошибки: трек 5 не делался. Один Docker-хост, единственные PostgreSQL, Redis и HAProxy остаются точками отказа. Если Redis жив, а удаление ключа при logout не прошло, кэш может жить до своего TTL. История сообщений не кэшируется. Миграция идёт один раз до старта реплик; совместимость новой схемы со старым бинарём под нагрузкой не проверялась. Пока HAProxy не снял backend, часть запросов на останавливаемую реплику завершается ошибкой соединения; повтор с тем же Idempotency-Key безопасен только для отправки сообщения.

Источники и использование ИИ: контракт contracts/openapi.json и contracts/README.md; Spring Boot 4.1.1, Spring Data JPA, spring-security-crypto, Spring Data Redis, Liquibase, Actuator, MapStruct 1.6.3, OpenAPI Generator 7.17.0, Bouncy Castle, PostgreSQL 16.10, Redis 7.4.6, HAProxy 3.2.6, Testcontainers. Реализация собрана в Cursor.

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
This commit is contained in:
ivanstorozhev
2026-10-29 20:00:59 +03:00
parent 0ab3a341aa
commit b9a899d510
84 changed files with 3645 additions and 14 deletions
+9
View File
@@ -0,0 +1,9 @@
id | author | dateexecuted
-----------------+--------+----------------------------
001-users | lab2 | 2026-10-29 15:45:56.018437
002-sessions | lab2 | 2026-10-29 15:45:56.031359
003-chats | lab2 | 2026-10-29 15:45:56.132238
004-messages | lab2 | 2026-10-29 15:45:56.217346
005-idempotency | lab3 | 2026-10-29 15:45:56.228835
(5 rows)
+10
View File
@@ -0,0 +1,10 @@
Limit (cost=0.29..5.11 rows=50 width=24) (actual time=0.009..0.020 rows=50 loops=1)
Buffers: shared hit=5
-> Index Only Scan using messages_history_idx on messages (cost=0.29..482.66 rows=5003 width=24) (actual time=0.009..0.017 rows=50 loops=1)
Index Cond: ((chat_id = 'a3e4d9b4-2c6b-47af-913e-663e57f5cff3'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 03:00:05+03'::timestamp with time zone, '677ea6b1-d3fb-471f-828b-16ca887b7a0d'::uuid)))
Heap Fetches: 50
Buffers: shared hit=5
Planning:
Buffers: shared hit=33
Planning Time: 0.116 ms
Execution Time: 0.035 ms
+2
View File
@@ -0,0 +1,2 @@
messenger-lab3-api-2 Up 33 seconds (healthy) 6cf753eaeaaf
messenger-lab3-api-1 Exited (143) 14 seconds ago 60a47156672c
+4
View File
@@ -0,0 +1,4 @@
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 119, "failed_attempts": 1, "first_recovery_seconds": 1.108}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
+2
View File
@@ -0,0 +1,2 @@
messenger-lab3-api-2 Up About a minute (healthy) 6cf753eaeaaf
messenger-lab3-api-1 Exited (143) 14 seconds ago 60a47156672c
+4
View File
@@ -0,0 +1,4 @@
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 115, "failed_attempts": 1, "first_recovery_seconds": 1.389}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
+2
View File
@@ -0,0 +1,2 @@
messenger-lab3-api-2 Exited (143) Less than a second ago 6cf753eaeaaf
messenger-lab3-api-1 Up 15 seconds (healthy) 60a47156672c
+5
View File
@@ -0,0 +1,5 @@
/messenger-lab3-api-1 cpus=1000000000 memory=1073741824 ports={}
/messenger-lab3-api-2 cpus=1000000000 memory=1073741824 ports={}
/messenger-lab3-postgres-1 cpus=1000000000 memory=536870912 ports={}
/messenger-lab3-redis-1 cpus=250000000 memory=134217728 ports={}
/messenger-lab3-lb-1 cpus=250000000 memory=134217728 ports={"8080/tcp":[{"HostIp":"127.0.0.1","HostPort":"8080"}]}
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 3,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 25.0,
"elapsed_seconds": 25.014,
"concurrency": 4,
"successful_requests": 11911,
"failed_requests": 23,
"error_ratio": 0.001927,
"successful_rps": 476.173,
"successful_latency_ms": {
"p50": 3.952,
"p95": 50.775,
"p99": 69.867
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 3,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 20.0,
"elapsed_seconds": 20.008,
"concurrency": 4,
"successful_requests": 12968,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 648.13,
"successful_latency_ms": {
"p50": 3.643,
"p95": 19.829,
"p99": 64.05
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+5
View File
@@ -0,0 +1,5 @@
/messenger-lab3-api-1 2026-10-29T15:48:37.42114101Z running
/messenger-lab3-api-2 2026-10-29T15:48:37.439325885Z running
/messenger-lab3-postgres-1 2026-10-29T15:48:37.372990802Z running
/messenger-lab3-redis-1 2026-10-29T15:48:37.347089969Z running
/messenger-lab3-lb-1 2026-10-29T15:48:37.320627844Z running
+5
View File
@@ -0,0 +1,5 @@
/messenger-lab3-api-1 2026-10-29T15:48:00.980211841Z running
/messenger-lab3-api-2 2026-10-29T15:48:00.893822341Z running
/messenger-lab3-postgres-1 2026-10-29T15:45:39.74062047Z running
/messenger-lab3-redis-1 2026-10-29T15:45:39.740035512Z running
/messenger-lab3-lb-1 2026-10-29T15:48:11.571522721Z running
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 3,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 90.0,
"elapsed_seconds": 90.007,
"concurrency": 4,
"successful_requests": 66264,
"failed_requests": 797,
"error_ratio": 0.011885,
"successful_rps": 736.209,
"successful_latency_ms": {
"p50": 3.389,
"p95": 11.779,
"p99": 49.555
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+7
View File
@@ -0,0 +1,7 @@
rolling 6cf753eaeaaf stop 2026-10-29T15:51:51Z
rolling 6cf753eaeaaf start 2026-10-29T15:51:51Z
rolling 6cf753eaeaaf healthy 2026-10-29T15:52:01Z
rolling 60a47156672c stop 2026-10-29T15:52:01Z
rolling 60a47156672c start 2026-10-29T15:52:02Z
rolling 60a47156672c healthy 2026-10-29T15:52:12Z
rolling update finished 2026-10-29T15:52:12Z
+8
View File
@@ -0,0 +1,8 @@
messenger-lab3-api-2 cpu=2.18% mem=384MiB / 1GiB
messenger-lab3-api-1 cpu=0.54% mem=389.5MiB / 1GiB
messenger-lab3-lb-1 cpu=0.24% mem=17.15MiB / 128MiB
messenger-lab3-postgres-1 cpu=0.11% mem=64MiB / 512MiB
messenger-lab3-redis-1 cpu=0.62% mem=9.906MiB / 128MiB
qualify-redis cpu=0.90% mem=21.06MiB / 7.653GiB
qualify-postgres-dev cpu=0.00% mem=58.75MiB / 7.653GiB
database-video_db-1 cpu=0.00% mem=45.18MiB / 7.653GiB
+3
View File
@@ -0,0 +1,3 @@
DRIVER VOLUME NAME
local messenger-lab3_postgres-data
local messenger-lab3_redis-data
+3
View File
@@ -0,0 +1,3 @@
DRIVER VOLUME NAME
local messenger-lab3_postgres-data
local messenger-lab3_redis-data