From 9c3e4fd1260fab215c539d44a16ddd036341e7ee Mon Sep 17 00:00:00 2001 From: EgorAnti Date: Thu, 5 Nov 2026 12:48:30 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20readiness=20LB=20=D0=B8=20=D1=80=D0=B5=D1=81?= =?UTF-8?q?=D1=83=D1=80=D1=81=D0=BD=D1=8B=D0=B5=20=D0=BB=D0=B8=D0=BC=D0=B8?= =?UTF-8?q?=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/pull_request_template.md | 7 +- Makefile | 5 +- README.md | 20 ++++ REPORT.md | 30 ++++- compose.yaml | 6 + evidence/readiness-and-limits-2026-11-05.md | 32 ++++++ infra/README.md | 16 ++- infra/nginx.conf | 14 +++ scripts/check_contract.py | 4 +- scripts/restart.example.sh | 0 scripts/restart.sh | 0 scripts/restore-api.sh | 0 scripts/rolling-update.sh | 0 scripts/stop-one.example.sh | 0 scripts/stop-one.sh | 0 scripts/swarm-lab-up.ps1 | 1 + .../config/SecurityConfig.java | 17 ++- .../controller/HealthController.java | 42 ++----- .../service/ReadinessService.java | 81 ++++++++++++++ .../web/ReadinessGuardFilter.java | 56 ++++++++++ .../web/ReadinessGuardFilterTest.java | 62 +++++++++++ student_tests/README.md | 3 + student_tests/readiness_gate.py | 104 ++++++++++++++++++ swarm/nginx.conf | 11 ++ 24 files changed, 466 insertions(+), 45 deletions(-) create mode 100644 evidence/readiness-and-limits-2026-11-05.md mode change 100644 => 100755 scripts/restart.example.sh mode change 100644 => 100755 scripts/restart.sh mode change 100644 => 100755 scripts/restore-api.sh mode change 100644 => 100755 scripts/rolling-update.sh mode change 100644 => 100755 scripts/stop-one.example.sh mode change 100644 => 100755 scripts/stop-one.sh create mode 100644 src/main/java/com/example/mtusi_messenger/service/ReadinessService.java create mode 100644 src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java create mode 100644 src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java create mode 100644 student_tests/readiness_gate.py diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 59e33ff6..77f2b940 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,7 +12,7 @@ - Основной стенд описан в `compose.yaml`: Nginx является единственной публичной точкой входа, за ним работают две stateless API-реплики с общей PostgreSQL и общим Redis. - Сессии и все данные, влияющие на корректность, хранятся в PostgreSQL; sticky session не используется. Реплики наблюдаются по `X-Instance-Id`. - Миграции вынесены в отдельный one-shot service `migrate`; в API-репликах Flyway отключён. -- Настроены `least_conn`, динамическое обновление Docker DNS, readiness, таймауты, graceful shutdown и пассивное исключение недоступного backend. +- Настроены `least_conn`, динамическое обновление Docker DNS, readiness guard, таймауты, graceful shutdown и пассивное исключение backend по 503. - Реализована общая идемпотентность отправки сообщения через `message_idempotency`, SHA-256 тела и транзакционную PostgreSQL advisory-блокировку. - Добавлены action scripts остановки/восстановления выбранной API-реплики, последовательный failover обеих реплик и rolling replacement под нагрузкой. - Для трека 5 добавлен отдельный трёхузловой Swarm-стенд: один manager, два workers, локальный registry, перенос API task при жёсткой потере worker и проверка сохранности подтверждённых сообщений. @@ -37,8 +37,10 @@ curl --fail http://localhost:8080/health/ready make check make test make test-idempotency +make test-readiness-gate make test-persistence ACTION_SCRIPT=scripts/restart.sh make test-failover-each ACTION_SCRIPT=scripts/stop-one.sh RESTORE_SCRIPT=scripts/restore-api.sh +chmod +x scripts/rolling-update.sh make test-rolling ACTION_SCRIPT=scripts/rolling-update.sh ``` @@ -54,6 +56,7 @@ make swarm-down - `make check` — PASS; основной `make test` через Nginx — `PASS: lab3 public API scenario`. - Конкурентная идемпотентность — 32 одновременных запроса через две реплики создали одно сообщение. +- Readiness gate — после временного переименования V3-таблицы обе API стали `unhealthy`, readiness и `/users/me` через LB вернули JSON 503; после восстановления вернулись `healthy`/200. - Последовательная остановка обеих Compose-реплик — 0 ошибок, 10,839/10,014 successful RPS, первая успешная операция через 1,306/2,672 s. - Rolling replacement — четыре instance ID, 12 147 успешных записей, 177 ошибок, 67,439 successful RPS, error ratio 1,4362%. - Потеря Swarm worker — API task перенесена с `worker2` на `worker1`; 165 чтений, 166 записей, 0 ошибок, первая успешная операция через 1,796 s; подтверждённые данные сохранены. @@ -63,7 +66,7 @@ make swarm-down - PostgreSQL не реплицирован и остаётся SPOF; отказ его узла не проверялся и не заявляется (`database_node_failed=false`). - Nginx, единственный Swarm manager, Redis, локальные volumes, underlay и физический Docker host также остаются SPOF. -- Nginx OSS использует пассивное runtime-исключение backend, а не активный health-check upstream. +- Nginx OSS использует пассивное исключение, поэтому API readiness guard возвращает 503 на бизнес-запрос неготовой реплики; Nginx повторяет его на другом peer, а при отсутствии готовых API возвращается 503. - Во время rolling replacement зафиксировано 1,4362% кратковременных ошибок; они намеренно не скрыты клиентским retry. - Swarm-опыт выполнен на DinD-узлах одного Windows/Docker Desktop host и не моделирует потерю разных физических серверов. diff --git a/Makefile b/Makefile index c1d00b88..2286fe9e 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test test-idempotency load test-persistence test-failover test-failover-each test-rolling swarm-up test-node-failover swarm-down +.PHONY: help check validate test test-idempotency test-readiness-gate load test-persistence test-failover test-failover-each test-rolling swarm-up test-node-failover swarm-down help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -21,6 +21,9 @@ test: test-idempotency: $(PYTHON) student_tests/idempotency_concurrent.py --base-url "$(BASE_URL)" $(TLS_ARGS) +test-readiness-gate: + $(PYTHON) student_tests/readiness_gate.py --base-url "$(BASE_URL)" $(TLS_ARGS) + load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) diff --git a/README.md b/README.md index 1ec655ca..e3f2c5f3 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,25 @@ hostname контейнера и останавливает только эту docker compose --env-file .env up -d --scale api=2 api ``` +Связь readiness с обслуживанием бизнес-запросов проверяется отдельно. Docker +вызывает `/health/ready` каждые 2 секунды; неуспешная проверка общей схемы +переводит конкретный Spring-процесс в `REFUSING_TRAFFIC`. Встроенный фильтр +возвращает 503 для всех бизнес-endpoint этой реплики до успешного probe. Nginx +повторяет такой ответ на другом peer и пассивно исключает отказавший адрес. Если +готовых API нет, `error_page` нормализует финальный ответ LB в JSON 503 с +`X-Request-Id`/`X-Instance-Id`, а не в HTML 502 или устаревший успешный ответ. +Первый dependency failure обнаруживается не позднее чем за 7 секунд: до 2 s до +следующего probe плюс SQL query timeout 5 s. Docker помечает контейнер +`unhealthy` после 15 последовательных отказов, то есть примерно через 30 s, +но readiness guard прекращает бизнес-трафик уже после первой ошибки probe. + +Воспроизведение с временным переименованием V3-таблицы и гарантированным +восстановлением в `finally`: + +```sh +make test-readiness-gate +``` + ### Проверки уровня 4 Обе реплики последовательно останавливаются с восстановлением между опытами: @@ -81,6 +100,7 @@ successful RPS, число ошибок и время первой успешн следующей. Проверка одновременно держит четыре потока записи: ```sh +chmod +x scripts/rolling-update.sh make test-rolling ACTION_SCRIPT=scripts/rolling-update.sh ``` diff --git a/REPORT.md b/REPORT.md index d1f696a4..055486f6 100644 --- a/REPORT.md +++ b/REPORT.md @@ -57,8 +57,8 @@ Nginx — единственный сервис, публикующий порт | Публичный LB | `nginx`, `nginx:1.27.4-bookworm` | `nginx -t`, каждые 2 s | нет | `127.0.0.1:8080 -> 80`, `backend` | не требуются | | API | `api`, локальный `hla-lab3-api:local` | `GET /health/ready`, каждые 2 s | нет | только `8080/backend` | параметры БД из `.env` через environment | | Миграции | `migrate`, тот же образ API | one-shot, код завершения | нет | `backend` | те же параметры БД | -| Источник истины | `postgres`, `postgres:16.4-bookworm` | `pg_isready`, каждые 2 s | `postgres-data` | только `5432/backend` | `DATABASE_PASSWORD` из `.env` | -| Общий кэш | `redis`, `redis:7.4-bookworm` | `redis-cli ping`, каждые 2 s | `redis-data`, AOF everysec | только `6379/backend` | наружу порт не открыт | +| Источник истины | `postgres`, `postgres:16.4-bookworm` | `pg_isready`, каждые 2 s | `postgres-data` | только `5432/backend`; 1 CPU/768 MiB | `DATABASE_PASSWORD` из `.env` | +| Общий кэш | `redis`, `redis:7.4-bookworm` | `redis-cli ping`, каждые 2 s | `redis-data`, AOF everysec | только `6379/backend`; 0,25 CPU/256 MiB | наружу порт не открыт | PostgreSQL хранит пользователей, Bearer-сессии, чаты, членство, сообщения и `message_idempotency`. Поэтому следующий запрос одного пользователя может @@ -133,9 +133,16 @@ Sticky session не используется. Она закрепляла бы Ошибка соединения определяется быстрее — в пределах 500 ms на попытку. Это укладывается в требование возобновить новые операции не позднее 10 секунд. -Nginx OSS использует пассивную runtime-проверку upstream: Docker readiness не -допускает ранний операторский запуск публичного маршрута, а отказ уже -работающего backend обнаруживается запросом и указанными таймерами. +Nginx OSS использует пассивную runtime-проверку upstream. Чтобы Docker health +не был отдельным от реального обслуживания, неуспешный schema probe переводит +Spring-процесс в `REFUSING_TRAFFIC`. Readiness guard этой реплики отвечает 503 +на любой бизнес-запрос до успешного восстановления. Nginx повторяет 503 на +другом peer и учитывает его как failure; если обе реплики неготовы, успешный +бизнес-ответ невозможен. Named location `@no_ready_api` преобразует финальный +Nginx 502/503/504 в контрактный JSON 503 с обязательными tracing headers. +Dependency failure обнаруживается максимум за 7 s: до 2 s до следующего probe +и до 5 s SQL query timeout. Docker ставит `unhealthy` после 15 ошибок, примерно +через 30 s, но guard блокирует бизнес-трафик после первой ошибки probe. ## 6. Readiness и graceful shutdown @@ -157,6 +164,14 @@ Docker вызывает readiness каждые 2 s, timeout — 2 s, start perio `stop_grace_period`. У Nginx `worker_shutdown_timeout=10s` и такой же `stop_grace_period`. +Регрессия исходного дефекта проверяется `make test-readiness-gate`: тест +временно переименовывает `message_idempotency`, ждёт `unhealthy` обеих API, +проверяет 503 от readiness и авторизованного `/users/me`, восстанавливает +таблицу в `finally` и требует возврата обеих реплик в `healthy`. +Фактический запуск 05.11.2026: обе реплики стали `unhealthy`, readiness и +авторизованный `/api/v1/users/me` через LB вернули JSON 503; после восстановления +таблицы обе реплики стали `healthy`, а те же запросы вернули 200. + ## 7. Общая идемпотентность сообщений Для `POST /api/v1/chats/{chatId}/messages` обязателен `Idempotency-Key`. @@ -237,6 +252,9 @@ PostgreSQL, а не память API и не Redis. - каждая Compose API-реплика: 0,75 CPU и 768 MiB; - Nginx: 0,25 CPU и 128 MiB; +- PostgreSQL: 1 CPU и 768 MiB; +- Redis: 0,25 CPU и 256 MiB; +- one-shot `migrate`: 0,75 CPU и 768 MiB; - API не публикует host port; - volumes есть только у PostgreSQL и Redis; - `container_name` отсутствует; @@ -251,6 +269,7 @@ PostgreSQL, а не память API и не Redis. четыре закрытых потока записи: ```sh +chmod +x scripts/rolling-update.sh make test-rolling ACTION_SCRIPT=scripts/rolling-update.sh ``` @@ -368,6 +387,7 @@ storage или физического host не переживается и не | Структура и синтаксис | `make check` | PASS | | Основной API через LB | `make test` | PASS | | Общая идемпотентность | `make test-idempotency` | 32 запроса, 2 реплики, 1 сообщение | +| Readiness блокирует бизнес-трафик | `make test-readiness-gate` | обе unhealthy-реплики отвечают 503 и восстанавливаются | | Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | прежние token и данные доступны | | Выбранная реплика | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | чтение/запись продолжаются | | Каждая реплика | `make test-failover-each ...` | 0 ошибок, recovery 1,306/2,672 s | diff --git a/compose.yaml b/compose.yaml index de14a7f5..b7ecc88f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -37,6 +37,8 @@ services: timeout: 2s retries: 30 restart: unless-stopped + cpus: 1.0 + mem_limit: 768m networks: [backend] redis: @@ -50,6 +52,8 @@ services: timeout: 2s retries: 30 restart: unless-stopped + cpus: 0.25 + mem_limit: 256m networks: [backend] # One-shot Flyway runner. It is invoked explicitly before API replicas. @@ -66,6 +70,8 @@ services: redis: condition: service_healthy restart: "no" + cpus: 0.75 + mem_limit: 768m networks: [backend] api: diff --git a/evidence/readiness-and-limits-2026-11-05.md b/evidence/readiness-and-limits-2026-11-05.md new file mode 100644 index 00000000..03d6081c --- /dev/null +++ b/evidence/readiness-and-limits-2026-11-05.md @@ -0,0 +1,32 @@ +# Readiness gate and Compose limits — 2026-11-05 + +Command: + +```text +python -B student_tests/readiness_gate.py --base-url http://localhost:8080 +``` + +Observed result: + +```text +PASS: 2 unhealthy API containers refused business traffic with 503 and recovered after schema restoration +table_state=true|false +``` + +The test temporarily renamed `message_idempotency`, waited until both Docker +API health states became `unhealthy`, and verified JSON 503 from both +`/health/ready` and authenticated `/api/v1/users/me` through Nginx. Its +`finally` block restored the table. Both API containers then became `healthy`, +and readiness/business requests returned 200. + +Applied `docker inspect` values: + +| Service | NanoCpus | Memory bytes | +| --- | ---: | ---: | +| PostgreSQL | 1,000,000,000 | 805,306,368 | +| Redis | 250,000,000 | 268,435,456 | +| API (each) | 750,000,000 | 805,306,368 | +| Nginx | 250,000,000 | 134,217,728 | + +The one-shot Compose migration service is configured with 0.75 CPU and 768 MiB. +The Swarm migration job uses the same explicit limits. diff --git a/infra/README.md b/infra/README.md index 262afec2..25c63559 100644 --- a/infra/README.md +++ b/infra/README.md @@ -21,6 +21,18 @@ connect timeout 500 ms, read/send timeout 4 s, две upstream-попытки и Docker DNS с TTL 2 s. Максимальное обнаружение зависшего backend — 4 s; максимум двух последовательных timeout-попыток — около 8.5 s. +Неуспешный schema probe публикует Spring-состояние `REFUSING_TRAFFIC`, и +readiness guard до аутентификации отвечает 503 на любой бизнес-запрос этой +реплики. Nginx настроен повторять 503 на другом peer и учитывать ответ как +пассивный failure. Поэтому Docker health не используется как недоступный Nginx +API: готовность связана с фактическим ответом backend. При восстановлении схемы +следующий probe возвращает процесс в `ACCEPTING_TRAFFIC`. +Когда готовы ноль peer, named location `@no_ready_api` преобразует внутренний +Nginx 502/финальный upstream 503/504 в контрактный JSON 503. +Граница обнаружения dependency failure — 7 s (период 2 s плюс query timeout +5 s). Docker status становится `unhealthy` примерно через 30 s из-за +`retries=15`, но это не задерживает readiness guard. + Flyway разрешён только в one-shot service `migrate`. У API задано `FLYWAY_ENABLED=false`, поэтому запуск нескольких реплик не создаёт гонку инициализации схемы. @@ -29,7 +41,9 @@ Restart hook поднимает зависимости по фазам и не API-реплики не стали healthy. Это не позволяет Docker DNS объявить прогревающуюся реплику через уже доступную публичную точку входа. -API ограничен 0.75 CPU и 768 MiB на контейнер, Nginx — 0.25 CPU и 128 MiB. +PostgreSQL ограничен 1 CPU и 768 MiB, Redis — 0.25 CPU и 256 MiB, one-shot +migrate — 0.75 CPU и 768 MiB, API — 0.75 CPU и 768 MiB на контейнер, Nginx — +0.25 CPU и 128 MiB. Порт публикует только Nginx. PostgreSQL и Redis имеют собственные volumes; API и Nginx постоянных volumes не имеют. `container_name` не используется, поэтому один Compose-service `api` масштабируется параметром `--scale`. diff --git a/infra/nginx.conf b/infra/nginx.conf index 04ed5162..16050ab7 100644 --- a/infra/nginx.conf +++ b/infra/nginx.conf @@ -24,6 +24,8 @@ http { server { listen 80; server_name _; + proxy_intercept_errors on; + error_page 502 503 504 = @no_ready_api; location = /nginx-health { access_log off; @@ -31,6 +33,18 @@ http { return 200 '{"status":"ok"}'; } + # After both peers have refused traffic or become unreachable, Nginx + # would normally emit its own HTML 502. Keep the public API contract: + # no ready backend is a JSON 503 with the required tracing headers. + location @no_ready_api { + internal; + default_type application/json; + add_header X-Request-Id $request_id always; + add_header X-Instance-Id nginx always; + add_header Cache-Control "no-store" always; + return 503 '{"error":{"code":"unavailable","message":"No ready API backend","request_id":"$request_id"}}'; + } + # Message POST is the only non-idempotent HTTP method that is safe to # replay here: the API requires Idempotency-Key and commits the message # together with its shared PostgreSQL idempotency record. diff --git a/scripts/check_contract.py b/scripts/check_contract.py index dcb34dfa..adb4b9e1 100644 --- a/scripts/check_contract.py +++ b/scripts/check_contract.py @@ -40,7 +40,9 @@ def main(): assert 'X-Instance-Id' in response['headers'] assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2) assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4) - for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')): + for file in (list((ROOT/'tests').glob('*.py')) + + list((ROOT/'student_tests').glob('*.py')) + + list((ROOT/'scripts').glob('*.py'))): ast.parse(file.read_text(),filename=str(file)) for file in ROOT.rglob('*.json'): if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts): diff --git a/scripts/restart.example.sh b/scripts/restart.example.sh old mode 100644 new mode 100755 diff --git a/scripts/restart.sh b/scripts/restart.sh old mode 100644 new mode 100755 diff --git a/scripts/restore-api.sh b/scripts/restore-api.sh old mode 100644 new mode 100755 diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh old mode 100644 new mode 100755 diff --git a/scripts/stop-one.example.sh b/scripts/stop-one.example.sh old mode 100644 new mode 100755 diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh old mode 100644 new mode 100755 diff --git a/scripts/swarm-lab-up.ps1 b/scripts/swarm-lab-up.ps1 index 412af524..c010ed19 100644 --- a/scripts/swarm-lab-up.ps1 +++ b/scripts/swarm-lab-up.ps1 @@ -112,6 +112,7 @@ Invoke-Checked docker exec $manager docker service create --name hla-migrate ` --mode replicated-job --replicas 1 --max-concurrent 1 ` --network hla-state_backend --constraint node.labels.hla.state==true ` --restart-condition on-failure --restart-delay 3s ` + --limit-cpu 0.75 --limit-memory 768M ` --env "DATABASE_URL=jdbc:postgresql://hla-state_postgres:5432/$database" ` --env "DATABASE_USER=$user" --env "DATABASE_PASSWORD=$password" ` --env FLYWAY_ENABLED=true --env MIGRATE_ONLY=true ` diff --git a/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java b/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java index e38246af..f2b9ae41 100644 --- a/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java +++ b/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java @@ -4,6 +4,7 @@ import com.example.mtusi_messenger.security.ApiAuthenticationFilter; import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider; import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint; import com.example.mtusi_messenger.service.AuthenticationService; +import com.example.mtusi_messenger.web.ReadinessGuardFilter; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; @@ -61,10 +62,20 @@ public class SecurityConfig { return registration; } + @Bean + FilterRegistrationBean disableReadinessGuardServletRegistration( + ReadinessGuardFilter filter + ) { + var registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + @Bean SecurityFilterChain securityFilterChain( HttpSecurity http, ApiAuthenticationFilter apiAuthenticationFilter, + ReadinessGuardFilter readinessGuardFilter, @Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint ) throws Exception { http @@ -86,7 +97,11 @@ public class SecurityConfig { ).permitAll() .requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll() .anyRequest().authenticated()) - .addFilterBefore(apiAuthenticationFilter, AnonymousAuthenticationFilter.class); + // Refuse business traffic before authentication touches storage. + // Nginx retries this 503 on another peer and passively excludes + // the refusing replica according to max_fails/fail_timeout. + .addFilterBefore(readinessGuardFilter, AnonymousAuthenticationFilter.class) + .addFilterAfter(apiAuthenticationFilter, ReadinessGuardFilter.class); return http.build(); } } diff --git a/src/main/java/com/example/mtusi_messenger/controller/HealthController.java b/src/main/java/com/example/mtusi_messenger/controller/HealthController.java index 2b9abc35..e4bfec30 100644 --- a/src/main/java/com/example/mtusi_messenger/controller/HealthController.java +++ b/src/main/java/com/example/mtusi_messenger/controller/HealthController.java @@ -1,31 +1,18 @@ package com.example.mtusi_messenger.controller; import org.springframework.http.ResponseEntity; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.RedisCallback; -import org.springframework.boot.availability.ApplicationAvailability; -import org.springframework.boot.availability.ReadinessState; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.example.mtusi_messenger.dto.HealthResponse; import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.service.ReadinessService; @RestController public class HealthController { - private final JdbcTemplate jdbc; - private final StringRedisTemplate redis; - private final ApplicationAvailability availability; + private final ReadinessService readiness; - public HealthController( - JdbcTemplate jdbc, - StringRedisTemplate redis, - ApplicationAvailability availability - ) { - this.jdbc = jdbc; - this.redis = redis; - this.availability = availability; + public HealthController(ReadinessService readiness) { + this.readiness = readiness; } @GetMapping("/health/live") @@ -35,24 +22,11 @@ public class HealthController { @GetMapping("/health/ready") public ResponseEntity ready() { - if (availability.getReadinessState() != ReadinessState.ACCEPTING_TRAFFIC) { + // Always probe dependencies, even after a failure, so a restored schema + // can move this process back to ACCEPTING_TRAFFIC without a restart. + if (!readiness.probeDependencies() || !readiness.acceptsBusinessTraffic()) { throw ApiExceptions.unavailable("Application is not accepting traffic"); } - try { - // Warm the lazy Lettuce connection on every replica. Redis remains - // an optional cache: failure is ignored and business reads fall - // back to PostgreSQL. - redis.execute((RedisCallback) connection -> connection.ping()); - } catch (DataAccessException ignored) { - // Optional cache unavailable; PostgreSQL remains authoritative. - } - try { - // A schema-level probe prevents a replica from becoming ready - // before the separately executed migration job has completed. - jdbc.queryForObject("SELECT count(*) FROM message_idempotency", Long.class); - return ResponseEntity.ok(new HealthResponse("ok")); - } catch (DataAccessException e) { - throw ApiExceptions.unavailable("Database is unavailable"); - } + return ResponseEntity.ok(new HealthResponse("ok")); } } diff --git a/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java b/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java new file mode 100644 index 00000000..7600c4d9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java @@ -0,0 +1,81 @@ +package com.example.mtusi_messenger.service; + +import org.springframework.boot.availability.ApplicationAvailability; +import org.springframework.boot.availability.AvailabilityChangeEvent; +import org.springframework.boot.availability.ReadinessState; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.concurrent.atomic.AtomicBoolean; + +@Service +public class ReadinessService { + private final JdbcTemplate jdbc; + private final StringRedisTemplate redis; + private final ApplicationAvailability availability; + private final ApplicationEventPublisher events; + private final AtomicBoolean dependencyUnavailable = new AtomicBoolean(false); + private final AtomicBoolean shuttingDown = new AtomicBoolean(false); + + public ReadinessService( + JdbcTemplate jdbc, + StringRedisTemplate redis, + ApplicationAvailability availability, + ApplicationEventPublisher events + ) { + this.jdbc = jdbc; + this.redis = redis; + this.availability = availability; + this.events = events; + } + + public boolean probeDependencies() { + try { + // Redis is an optional cache. Ping only warms the lazy connection; + // its failure must not make the authoritative API unavailable. + redis.execute((RedisCallback) connection -> connection.ping()); + } catch (DataAccessException ignored) { + // PostgreSQL remains the source of truth. + } + + try { + // The schema-level probe also proves that the separate V3 migration + // completed before this replica is allowed to serve business traffic. + jdbc.queryForObject("SELECT count(*) FROM message_idempotency", Long.class); + markDependenciesAvailable(); + return true; + } catch (DataAccessException e) { + markDependenciesUnavailable(); + return false; + } + } + + public boolean acceptsBusinessTraffic() { + return !shuttingDown.get() + && !dependencyUnavailable.get() + && availability.getReadinessState() == ReadinessState.ACCEPTING_TRAFFIC; + } + + @EventListener(ContextClosedEvent.class) + void onContextClosed() { + shuttingDown.set(true); + } + + private void markDependenciesUnavailable() { + dependencyUnavailable.set(true); + AvailabilityChangeEvent.publish(events, this, ReadinessState.REFUSING_TRAFFIC); + } + + private void markDependenciesAvailable() { + boolean recovered = dependencyUnavailable.getAndSet(false); + if (recovered && !shuttingDown.get()) { + AvailabilityChangeEvent.publish(events, this, ReadinessState.ACCEPTING_TRAFFIC); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java b/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java new file mode 100644 index 00000000..c69594ea --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java @@ -0,0 +1,56 @@ +package com.example.mtusi_messenger.web; + +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.service.ReadinessService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Component +public class ReadinessGuardFilter extends OncePerRequestFilter { + private final ReadinessService readiness; + private final ObjectMapper mapper; + + public ReadinessGuardFilter(ReadinessService readiness, ObjectMapper mapper) { + this.readiness = readiness; + this.mapper = mapper; + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + return path.startsWith("/health/") + || path.equals("/swagger-ui.html") + || path.startsWith("/swagger-ui/") + || path.startsWith("/v3/api-docs/") + || path.equals("/v3/api-docs"); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + if (readiness.acceptsBusinessTraffic()) { + filterChain.doFilter(request, response); + return; + } + + response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE); + mapper.writeValue(response.getOutputStream(), new ErrorResponse( + new ErrorResponse.ErrorBody( + "unavailable", + "Application is not ready to serve business traffic", + requestId))); + } +} diff --git a/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java b/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java new file mode 100644 index 00000000..a8374d13 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java @@ -0,0 +1,62 @@ +package com.example.mtusi_messenger.web; + +import com.example.mtusi_messenger.service.ReadinessService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ReadinessGuardFilterTest { + private final ReadinessService readiness = mock(ReadinessService.class); + private final ObjectMapper mapper = new ObjectMapper(); + private final ReadinessGuardFilter filter = new ReadinessGuardFilter(readiness, mapper); + + @Test + void refusingReplicaRejectsBusinessTrafficBeforeItReachesTheChain() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(false); + var request = new MockHttpServletRequest("GET", "/api/v1/users/me"); + request.setAttribute(RequestIdFilter.ATTRIBUTE, "request-1"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertEquals(503, response.getStatus()); + assertNull(chain.getRequest()); + JsonNode body = mapper.readTree(response.getContentAsByteArray()); + assertEquals("unavailable", body.at("/error/code").asText()); + assertEquals("request-1", body.at("/error/request_id").asText()); + } + + @Test + void readyReplicaPassesBusinessTrafficToTheChain() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(true); + var request = new MockHttpServletRequest("GET", "/api/v1/users/me"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertSame(request, chain.getRequest()); + } + + @Test + void healthProbeIsNeverBlockedByTheBusinessGuard() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(false); + var request = new MockHttpServletRequest("GET", "/health/ready"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertSame(request, chain.getRequest()); + } +} diff --git a/student_tests/README.md b/student_tests/README.md index 0ac05425..a4b188ec 100644 --- a/student_tests/README.md +++ b/student_tests/README.md @@ -5,6 +5,9 @@ The course-provided black-box suite remains in `tests/`; Spring tests remain in `src/test/java`. - `idempotency_concurrent.py` — one key through multiple API replicas. +- `readiness_gate.py` — both replicas become unhealthy after the required + schema table disappears; readiness and business traffic must return 503, + then recover after the table is restored. - `failover_each.py` — sequential process failover of both Compose replicas. - `rolling_update.py` — sequential replacement under write load. - `node_failover.py` — hard loss of one worker in the disposable three-node diff --git a/student_tests/readiness_gate.py b/student_tests/readiness_gate.py new file mode 100644 index 00000000..1a9df4c6 --- /dev/null +++ b/student_tests/readiness_gate.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Reproduce and guard against serving business traffic from unready APIs.""" +from pathlib import Path +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, Failure, arguments, check, run + +ORIGINAL_TABLE = 'message_idempotency' +TEMPORARY_TABLE = 'message_idempotency_readiness_test' + + +def command(*args): + result = subprocess.run( + args, + cwd=ROOT, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False) + if result.returncode != 0: + output = result.stdout.strip() + raise Failure('command failed: ' + ' '.join(args[:3]) + + (': ' + output if output else '')) + return result.stdout.strip() + + +def rename_table(source, target): + sql = 'ALTER TABLE ' + source + ' RENAME TO ' + target + ';' + command( + 'docker', 'compose', 'exec', '-T', 'postgres', 'sh', '-ec', + 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" ' + '-d "$POSTGRES_DB" -c \'' + sql + '\'') + + +def api_container_ids(): + output = command('docker', 'compose', 'ps', '-q', 'api') + return [line.strip() for line in output.splitlines() if line.strip()] + + +def health_status(container_id): + return command( + 'docker', 'inspect', + '--format={{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}', + container_id) + + +def wait_for_all_health(expected, timeout): + deadline = time.monotonic() + timeout + last = [] + while time.monotonic() < deadline: + containers = api_container_ids() + last = [health_status(container) for container in containers] + if len(containers) >= 2 and all(value == expected for value in last): + return containers + time.sleep(1) + raise Failure('API health did not become ' + expected + + '; last statuses: ' + repr(last)) + + +def configure(parser): + parser.add_argument( + '--health-timeout', type=float, default=45.0, + help='seconds to wait for both Docker health states') + + +def main(): + args = arguments('Readiness must gate business traffic through the LB', configure) + client = Client(args.base_url, args.ca_file, timeout=8) + client.call('GET', '/health/ready', 200, schema='Health') + actor = client.user('readiness_gate') + + renamed = False + try: + rename_table(ORIGINAL_TABLE, TEMPORARY_TABLE) + renamed = True + containers = wait_for_all_health('unhealthy', args.health_timeout) + + client.call('GET', '/health/ready', 503) + instances = set() + for _ in range(8): + response = client.call( + 'GET', '/api/v1/users/me', 503, actor=actor) + instances.add(response['headers']['X-Instance-Id']) + check(instances, 'no refusing API instance was observed') + finally: + if renamed: + rename_table(TEMPORARY_TABLE, ORIGINAL_TABLE) + + wait_for_all_health('healthy', args.health_timeout) + # Nginx may retain a passive failure for fail_timeout=2s. + time.sleep(3) + client.call('GET', '/health/ready', 200, schema='Health') + client.call('GET', '/api/v1/users/me', 200, actor=actor, schema='User') + print('PASS: ' + str(len(containers)) + + ' unhealthy API containers refused business traffic with 503 ' + + 'and recovered after schema restoration') + + +if __name__ == '__main__': + run(main) diff --git a/swarm/nginx.conf b/swarm/nginx.conf index edd794c9..044151ce 100644 --- a/swarm/nginx.conf +++ b/swarm/nginx.conf @@ -21,12 +21,23 @@ http { server { listen 80; server_name _; + proxy_intercept_errors on; + error_page 502 503 504 = @no_ready_api; location = /nginx-health { default_type application/json; return 200 '{"status":"ok"}'; } + location @no_ready_api { + internal; + default_type application/json; + add_header X-Request-Id $request_id always; + add_header X-Instance-Id nginx always; + add_header Cache-Control "no-store" always; + return 503 '{"error":{"code":"unavailable","message":"No ready API backend","request_id":"$request_id"}}'; + } + location ~ ^/api/v1/chats/[0-9a-fA-F-]+/messages$ { proxy_pass http://api_backend; proxy_http_version 1.1;