forked from mtusi2026/mtusi2026lab3
feat: add evidence collection, experiment results and report
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
# Стенд: сервисы, порты, лимиты, секреты, миграции
|
||||
# date: 2026-11-01T14:23:40Z
|
||||
# commit: 210ff67 (dirty)
|
||||
|
||||
$ docker compose ps -a --format table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}
|
||||
SERVICE NAME IMAGE STATUS PORTS
|
||||
api messenger-lab3-api-10 mtusi-messenger-lab3-api:dev Up 6 minutes (healthy) 8080/tcp
|
||||
api messenger-lab3-api-9 mtusi-messenger-lab3-api:dev Up 6 minutes (healthy) 8080/tcp
|
||||
lb messenger-lab3-lb-1 haproxy:3.0.6-alpine Up 11 minutes 127.0.0.1:8080->8080/tcp
|
||||
migrate messenger-lab3-migrate-1 mtusi-messenger-lab3-migrate:dev Exited (0) 7 minutes ago
|
||||
postgres messenger-lab3-postgres-1 postgres:17.2-alpine Up 7 minutes (healthy) 5432/tcp
|
||||
redis messenger-lab3-redis-1 redis:7.4.1-alpine Up 8 minutes (healthy) 6379/tcp
|
||||
secrets-init messenger-lab3-secrets-init-1 alpine:3.20.3 Exited (0) 7 minutes ago
|
||||
tools messenger-lab3-tools-run-d623204458ed mtusi-messenger-lab3-tools:dev Up Less than a second
|
||||
|
||||
## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах)
|
||||
$ sh -c docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' $(docker compose ps -q)
|
||||
/messenger-lab3-api-10 cpus=500000000 memory=268435456
|
||||
/messenger-lab3-api-9 cpus=500000000 memory=268435456
|
||||
/messenger-lab3-lb-1 cpus=250000000 memory=67108864
|
||||
/messenger-lab3-postgres-1 cpus=1000000000 memory=536870912
|
||||
/messenger-lab3-redis-1 cpus=250000000 memory=134217728
|
||||
|
||||
## container_name не задан (одно имя сервиса масштабируется)
|
||||
$ sh -c docker compose config | grep -c container_name || true
|
||||
0
|
||||
|
||||
## Секреты: каждый сервис видит только свои файлы
|
||||
$ docker compose exec -T postgres ls /run/secrets
|
||||
pg_password
|
||||
|
||||
$ docker compose exec -T redis ls /run/secrets
|
||||
redis_password
|
||||
|
||||
$ docker compose exec -T api ls /run/secrets
|
||||
cache_url
|
||||
database_url
|
||||
|
||||
$ docker compose exec -T lb sh -c ls /run/secrets 2>/dev/null || echo "no /run/secrets"
|
||||
no /run/secrets
|
||||
|
||||
$ docker compose exec -T lb haproxy -v
|
||||
HAProxy version 3.0.6-c2c0090 2024/11/07 - https://haproxy.org/
|
||||
Status: long-term supported branch - will stop receiving fixes around Q2 2029.
|
||||
Known bugs: http://www.haproxy.org/bugs/bugs-3.0.6.html
|
||||
Running on: Linux 5.15.153.1-microsoft-standard-WSL2 #1 SMP Fri Mar 29 23:14:13 UTC 2024 x86_64
|
||||
|
||||
$ docker compose exec -T postgres postgres --version
|
||||
postgres (PostgreSQL) 17.2
|
||||
|
||||
$ docker compose exec -T redis redis-server --version
|
||||
Redis server v=7.4.1 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=a93ce81042b3a6d7
|
||||
|
||||
## Миграции: отдельный one-shot сервис, повторный запуск ничего не применяет
|
||||
$ docker compose run --rm migrate
|
||||
Container messenger-lab3-secrets-init-1 Created
|
||||
Container messenger-lab3-postgres-1 Running
|
||||
Container messenger-lab3-secrets-init-1 Starting
|
||||
Container messenger-lab3-secrets-init-1 Started
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Prisma schema loaded from prisma/schema.prisma
|
||||
Datasource "db": PostgreSQL database "messenger", schema "public" at "postgres:5432"
|
||||
|
||||
3 migrations found in prisma/migrations
|
||||
|
||||
|
||||
No pending migrations to apply.
|
||||
|
||||
$ docker compose run --rm --no-deps migrate sh -c export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code
|
||||
No difference detected.
|
||||
|
||||
|
||||
$ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at
|
||||
migration_name | finished_at
|
||||
---------------------------------+-------------------------------
|
||||
20261021000000_init | 2026-11-01 10:26:06.913822+00
|
||||
20261021010000_auth_sessions | 2026-11-01 10:26:06.924458+00
|
||||
20261101000000_idempotency_keys | 2026-11-01 11:03:29.670935+00
|
||||
(3 rows)
|
||||
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
{
|
||||
"scenario": "sequential failover of each api replica",
|
||||
"resources_under_load": [
|
||||
"messenger-lab3-api-10 cpu=45.52% mem=115.8MiB / 256MiB",
|
||||
"messenger-lab3-api-9 cpu=47.28% mem=96.32MiB / 256MiB",
|
||||
"messenger-lab3-lb-1 cpu=13.68% mem=16.25MiB / 64MiB",
|
||||
"messenger-lab3-postgres-1 cpu=24.15% mem=77.63MiB / 512MiB",
|
||||
"messenger-lab3-redis-1 cpu=2.08% mem=9.832MiB / 128MiB"
|
||||
],
|
||||
"replicas": [
|
||||
{
|
||||
"container": "/messenger-lab3-api-10 running image=f80c910ed3d1",
|
||||
"action": "docker kill (SIGKILL)",
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"successful_writes": 777,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 155.4,
|
||||
"latency_ms_successful": {
|
||||
"p50": 10.6,
|
||||
"p95": 83.1,
|
||||
"p99": 158.6
|
||||
},
|
||||
"max_write_gap_seconds": 0.096,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
},
|
||||
"stop_command_seconds": 0.478,
|
||||
"target_last_success_after_stop_seconds": null,
|
||||
"outage_window": {
|
||||
"seconds": 10.478,
|
||||
"successful_writes": 847,
|
||||
"failed_attempts": 3,
|
||||
"error_ratio": 0.0035,
|
||||
"successful_rps": 80.8,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.7,
|
||||
"p95": 88.5,
|
||||
"p99": 1012.5
|
||||
},
|
||||
"max_write_gap_seconds": 0.989,
|
||||
"instances": [
|
||||
"75ad096eed0a"
|
||||
]
|
||||
},
|
||||
"restore_until_healthy_seconds": 5.506,
|
||||
"restore_until_serving_seconds": 3.616,
|
||||
"after_restore": {
|
||||
"seconds": 5.036,
|
||||
"successful_writes": 771,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 153.1,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.2,
|
||||
"p95": 80.5,
|
||||
"p99": 152.1
|
||||
},
|
||||
"max_write_gap_seconds": 0.147,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"container": "/messenger-lab3-api-9 running image=f80c910ed3d1",
|
||||
"action": "docker kill (SIGKILL)",
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"successful_writes": 769,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 153.8,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.2,
|
||||
"p95": 80.5,
|
||||
"p99": 152.1
|
||||
},
|
||||
"max_write_gap_seconds": 0.147,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
},
|
||||
"stop_command_seconds": 0.503,
|
||||
"target_last_success_after_stop_seconds": 0.001,
|
||||
"outage_window": {
|
||||
"seconds": 10.503,
|
||||
"successful_writes": 706,
|
||||
"failed_attempts": 2,
|
||||
"error_ratio": 0.0028,
|
||||
"successful_rps": 67.2,
|
||||
"latency_ms_successful": {
|
||||
"p50": 13.6,
|
||||
"p95": 98.1,
|
||||
"p99": 1012.2
|
||||
},
|
||||
"max_write_gap_seconds": 0.994,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
},
|
||||
"restore_until_healthy_seconds": 5.898,
|
||||
"restore_until_serving_seconds": 3.356,
|
||||
"after_restore": {
|
||||
"seconds": 5.021,
|
||||
"successful_writes": 827,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 164.7,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.2,
|
||||
"p95": 73.8,
|
||||
"p99": 87.4
|
||||
},
|
||||
"max_write_gap_seconds": 0.092,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"dataset": {
|
||||
"messages_in_db_before": 81019,
|
||||
"messages_in_db_after": 86799
|
||||
},
|
||||
"history": {
|
||||
"confirmed": 5780,
|
||||
"stored": 5780,
|
||||
"lost_confirmed": 0,
|
||||
"duplicates": 0
|
||||
},
|
||||
"load": {
|
||||
"workers": 4,
|
||||
"model": "closed loop, POST message",
|
||||
"warmup_seconds": 5,
|
||||
"client_timeout_seconds": 2,
|
||||
"retry": "same Idempotency-Key until success"
|
||||
},
|
||||
"date": "2026-11-01T14:26:57Z"
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
{
|
||||
"scenario": "sequential failover of each api replica",
|
||||
"resources_under_load": [
|
||||
"messenger-lab3-api-10 cpu=50.96% mem=95.24MiB / 256MiB",
|
||||
"messenger-lab3-api-9 cpu=43.28% mem=130.2MiB / 256MiB",
|
||||
"messenger-lab3-lb-1 cpu=12.66% mem=13.96MiB / 64MiB",
|
||||
"messenger-lab3-postgres-1 cpu=24.59% mem=60.97MiB / 512MiB",
|
||||
"messenger-lab3-redis-1 cpu=2.19% mem=9.832MiB / 128MiB"
|
||||
],
|
||||
"replicas": [
|
||||
{
|
||||
"container": "/messenger-lab3-api-10 running image=f80c910ed3d1",
|
||||
"action": "docker stop (SIGTERM, graceful)",
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"successful_writes": 784,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 156.8,
|
||||
"latency_ms_successful": {
|
||||
"p50": 10.6,
|
||||
"p95": 78.0,
|
||||
"p99": 170.9
|
||||
},
|
||||
"max_write_gap_seconds": 0.088,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
},
|
||||
"stop_command_seconds": 3.464,
|
||||
"target_last_success_after_stop_seconds": 1.353,
|
||||
"outage_window": {
|
||||
"seconds": 13.464,
|
||||
"successful_writes": 1746,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 129.7,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.1,
|
||||
"p95": 85.7,
|
||||
"p99": 172.3
|
||||
},
|
||||
"max_write_gap_seconds": 0.457,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
},
|
||||
"restore_until_healthy_seconds": 5.621,
|
||||
"restore_until_serving_seconds": 3.995,
|
||||
"after_restore": {
|
||||
"seconds": 5.026,
|
||||
"successful_writes": 898,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 178.7,
|
||||
"latency_ms_successful": {
|
||||
"p50": 9.8,
|
||||
"p95": 73.4,
|
||||
"p99": 88.6
|
||||
},
|
||||
"max_write_gap_seconds": 0.088,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"container": "/messenger-lab3-api-9 running image=f80c910ed3d1",
|
||||
"action": "docker stop (SIGTERM, graceful)",
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"successful_writes": 898,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 179.6,
|
||||
"latency_ms_successful": {
|
||||
"p50": 9.8,
|
||||
"p95": 73.4,
|
||||
"p99": 88.6
|
||||
},
|
||||
"max_write_gap_seconds": 0.088,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
},
|
||||
"stop_command_seconds": 3.471,
|
||||
"target_last_success_after_stop_seconds": 1.969,
|
||||
"outage_window": {
|
||||
"seconds": 13.471,
|
||||
"successful_writes": 1791,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 132.9,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.0,
|
||||
"p95": 87.3,
|
||||
"p99": 102.5
|
||||
},
|
||||
"max_write_gap_seconds": 0.103,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
},
|
||||
"restore_until_healthy_seconds": 5.753,
|
||||
"restore_until_serving_seconds": 3.591,
|
||||
"after_restore": {
|
||||
"seconds": 5.032,
|
||||
"successful_writes": 854,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 169.7,
|
||||
"latency_ms_successful": {
|
||||
"p50": 10.3,
|
||||
"p95": 76.0,
|
||||
"p99": 92.6
|
||||
},
|
||||
"max_write_gap_seconds": 0.078,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"dataset": {
|
||||
"messages_in_db_before": 72994,
|
||||
"messages_in_db_after": 81019
|
||||
},
|
||||
"history": {
|
||||
"confirmed": 8025,
|
||||
"stored": 8025,
|
||||
"lost_confirmed": 0,
|
||||
"duplicates": 0
|
||||
},
|
||||
"load": {
|
||||
"workers": 4,
|
||||
"model": "closed loop, POST message",
|
||||
"warmup_seconds": 5,
|
||||
"client_timeout_seconds": 2,
|
||||
"retry": "same Idempotency-Key until success"
|
||||
},
|
||||
"date": "2026-11-01T14:26:05Z"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# make test-failover: stop-one.sh останавливает реплику, обслужившую тест; затем вторую
|
||||
# date: 2026-11-01T14:24:26Z
|
||||
# commit: 210ff67 (dirty)
|
||||
|
||||
## Прогон 1
|
||||
### до
|
||||
/messenger-lab3-api-10 id=2701b0d53e0f running exit=0 finished=2026-11-01T14:24:22.65057843Z
|
||||
/messenger-lab3-api-9 id=75ad096eed0a running exit=0 finished=2026-11-01T14:24:22.658060985Z
|
||||
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 126, "failed_attempts": 0, "first_recovery_seconds": 3.475}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
### после: остановленная реплика Exited (0) — штатное завершение по SIGTERM
|
||||
/messenger-lab3-api-10 id=2701b0d53e0f running exit=0 finished=2026-11-01T14:24:22.65057843Z
|
||||
/messenger-lab3-api-9 id=75ad096eed0a exited exit=0 finished=2026-11-01T14:24:30.362206587Z
|
||||
|
||||
### журнал HAProxy
|
||||
Server api/api2 is UP, reason: Layer7 check passed, code: 200, check duration: 2ms. 1 active and 0 backup servers online. 0 sessions requeued, 0 total in queue.
|
||||
Server api/api1 is UP, reason: Layer7 check passed, code: 200, check duration: 1ms. 2 active and 0 backup servers online. 0 sessions requeued, 0 total in queue.
|
||||
Server api/api2 is DOWN, reason: Layer7 wrong status, code: 503, info: "Service Unavailable", check duration: 1ms. 1 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
|
||||
Server api/api2 was DOWN and now enters maintenance (No IP for server ).
|
||||
|
||||
## Прогон 2
|
||||
### до
|
||||
/messenger-lab3-api-10 id=2701b0d53e0f running exit=0 finished=2026-11-01T14:24:22.65057843Z
|
||||
/messenger-lab3-api-9 id=75ad096eed0a running exit=0 finished=2026-11-01T14:24:30.362206587Z
|
||||
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 3.43}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
### после: остановленная реплика Exited (0) — штатное завершение по SIGTERM
|
||||
/messenger-lab3-api-10 id=2701b0d53e0f exited exit=0 finished=2026-11-01T14:24:49.840732823Z
|
||||
/messenger-lab3-api-9 id=75ad096eed0a running exit=0 finished=2026-11-01T14:24:30.362206587Z
|
||||
|
||||
### журнал HAProxy
|
||||
Server api/api1 is DOWN, reason: Layer7 wrong status, code: 503, info: "Service Unavailable", check duration: 1ms. 1 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
|
||||
Server api/api1 was DOWN and now enters maintenance (No IP for server ).
|
||||
|
||||
## Проверка guard: stop-one.sh отказывается останавливать не api
|
||||
$ env TARGET_INSTANCE_ID=eb4e6be5ba1d sh scripts/stop-one.sh
|
||||
refusing to stop eb4e6be5ba1d: not an api replica of messenger-lab3 (messenger-lab3/postgres)
|
||||
EXIT CODE 1
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
# Отказы зависимостей, ошибки LB, expiry
|
||||
# date: 2026-11-01T14:27:40Z
|
||||
# commit: 210ff67 (dirty)
|
||||
|
||||
## 1. Redis остановлен: вход и Bearer через PostgreSQL; logout — 503 без отзыва (токен остаётся действующим)
|
||||
$ docker compose stop redis
|
||||
Container messenger-lab3-redis-1 Stopping
|
||||
Container messenger-lab3-redis-1 Stopped
|
||||
|
||||
$ python3 scripts/probe.py logout
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:27:41.083Z
|
||||
GET /api/v1/users/me -> 200
|
||||
DELETE /api/v1/auth/sessions/current -> 503 {"error": {"code": "unavailable", "message": "session cache unavailable", "request_id": "7aff0b0d-d263-4bad-ae24-534ed11e5885"}}
|
||||
GET /api/v1/users/me -> 200
|
||||
|
||||
$ docker compose start redis
|
||||
Container messenger-lab3-secrets-init-1 Starting
|
||||
Container messenger-lab3-secrets-init-1 Started
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Container messenger-lab3-redis-1 Starting
|
||||
Container messenger-lab3-redis-1 Started
|
||||
|
||||
## 2. Redis снова доступен: logout отзывает токен на всех репликах
|
||||
$ python3 scripts/probe.py logout
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:27:46.084Z
|
||||
GET /api/v1/users/me -> 200
|
||||
DELETE /api/v1/auth/sessions/current -> 204
|
||||
GET /api/v1/users/me -> 401
|
||||
|
||||
## 3. PostgreSQL остановлен: live 200, запрос с токеном — 503 без внутренних деталей, аноним — 401
|
||||
$ docker compose stop postgres
|
||||
Container messenger-lab3-postgres-1 Stopping
|
||||
Container messenger-lab3-postgres-1 Stopped
|
||||
|
||||
$ python3 scripts/probe.py status GET /health/live
|
||||
GET /health/live (anonymous) -> 200 {"status": "ok"}
|
||||
|
||||
$ python3 scripts/probe.py status GET /api/v1/chats Bearer unknown-token
|
||||
GET /api/v1/chats (Bearer unknown-token) -> 503 {"error": {"code": "unavailable", "message": "database unavailable", "request_id": "084e5aa0-f8c4-44c2-91a6-5672ab0fe7f9"}}
|
||||
|
||||
$ python3 scripts/probe.py status GET /api/v1/users/me
|
||||
GET /api/v1/users/me (anonymous) -> 503 {"error": {"code": "unavailable", "message": "no API replica available", "request_id": "f041cada-528c-4d13-bf1e-fefc33ec422e"}}
|
||||
|
||||
$ docker compose start postgres
|
||||
Container messenger-lab3-secrets-init-1 Starting
|
||||
Container messenger-lab3-secrets-init-1 Started
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Container messenger-lab3-postgres-1 Starting
|
||||
Container messenger-lab3-postgres-1 Started
|
||||
|
||||
$ python3 scripts/probe.py ready
|
||||
ready
|
||||
|
||||
## 4. Все реплики API остановлены: LB отвечает 503 в формате ошибки контракта
|
||||
$ docker compose stop api
|
||||
Container messenger-lab3-api-11 Stopping
|
||||
Container messenger-lab3-api-12 Stopping
|
||||
Container messenger-lab3-api-12 Stopped
|
||||
Container messenger-lab3-api-11 Stopped
|
||||
|
||||
$ python3 scripts/probe.py status GET /api/v1/users/me
|
||||
GET /api/v1/users/me (anonymous) -> 503 {"error": {"code": "unavailable", "message": "no API replica available", "request_id": "4e1d1184-174b-47c6-9406-6d5e3e7457de"}}
|
||||
|
||||
$ docker compose start api
|
||||
Container messenger-lab3-secrets-init-1 Starting
|
||||
Container messenger-lab3-secrets-init-1 Started
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Container messenger-lab3-postgres-1 Waiting
|
||||
Container messenger-lab3-postgres-1 Healthy
|
||||
Container messenger-lab3-migrate-1 Starting
|
||||
Container messenger-lab3-migrate-1 Started
|
||||
Container messenger-lab3-migrate-1 Waiting
|
||||
Container messenger-lab3-migrate-1 Exited
|
||||
Container messenger-lab3-api-12 Starting
|
||||
Container messenger-lab3-api-12 Started
|
||||
Container messenger-lab3-api-11 Starting
|
||||
Container messenger-lab3-api-11 Started
|
||||
|
||||
$ python3 scripts/probe.py ready
|
||||
ready
|
||||
|
||||
## 5. Живая, но неготовая реплика: PostgreSQL отклоняет подключения только от одной API (pg_hba reject)
|
||||
target=b446d5242566 ip=172.25.0.6
|
||||
$ docker exec b446d5242566 node -e let n=0;const g=p=>require('http').get('http://127.0.0.1:8080'+p,r=>{console.log(p,r.statusCode);r.resume();if(++n===2)process.exit(0)});g('/health/live');g('/health/ready')
|
||||
/health/live 200
|
||||
/health/ready 503
|
||||
|
||||
$ python3 scripts/probe.py instances 10
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:28:12.845Z
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
|
||||
Server api/api2 is UP, reason: Layer7 check passed, code: 200, check duration: 2ms. 2 active and 0 backup servers online. 0 sessions requeued, 0 total in queue.
|
||||
Server api/api2 is DOWN, reason: Layer7 wrong status, code: 503, info: "Service Unavailable", check duration: 4ms. 1 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
|
||||
|
||||
### доступ возвращён: реплика снова готова и получает запросы
|
||||
$ python3 scripts/probe.py instances 6
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:28:17.742Z
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: b446d5242566
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: b446d5242566
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 18dde5d7e3c7
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: b446d5242566
|
||||
|
||||
## 6. Expiry: реплики пересозданы с SESSION_TTL_SECONDS=2
|
||||
$ sh -c docker exec $(docker compose ps -q api | head -1) printenv SESSION_TTL_SECONDS
|
||||
2
|
||||
|
||||
$ python3 scripts/probe.py expiry 2
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T14:28:30.603Z
|
||||
GET /api/v1/users/me (fresh) -> 200
|
||||
GET /api/v1/users/me (after 3s) -> 401
|
||||
|
||||
$ python3 scripts/probe.py ready
|
||||
ready
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"scenario": "parallel POST with one Idempotency-Key through LB",
|
||||
"requests": 20,
|
||||
"all_201": true,
|
||||
"distinct_message_ids": 1,
|
||||
"instances": [
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a"
|
||||
],
|
||||
"messages_in_history": 1,
|
||||
"date": "2026-11-01T14:25:07Z"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
# make test-persistence: restart.sh перезапускает postgres, redis, api, lb с сохранением volumes
|
||||
# date: 2026-11-01T14:24:18Z
|
||||
# commit: 210ff67 (dirty)
|
||||
|
||||
## до
|
||||
/messenger-lab3-api-10 running started=2026-11-01T14:17:40.379508837Z
|
||||
/messenger-lab3-api-9 running started=2026-11-01T14:17:40.671088423Z
|
||||
/messenger-lab3-lb-1 running started=2026-11-01T14:12:03.995670618Z
|
||||
/messenger-lab3-postgres-1 running started=2026-11-01T14:15:47.035908462Z
|
||||
/messenger-lab3-redis-1 running started=2026-11-01T14:15:35.848126753Z
|
||||
|
||||
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://lb:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
## после
|
||||
/messenger-lab3-api-10 running started=2026-11-01T14:24:23.200745127Z
|
||||
/messenger-lab3-api-9 running started=2026-11-01T14:24:23.330709545Z
|
||||
/messenger-lab3-lb-1 running started=2026-11-01T14:24:20.477359115Z
|
||||
/messenger-lab3-postgres-1 running started=2026-11-01T14:24:20.361554543Z
|
||||
/messenger-lab3-redis-1 running started=2026-11-01T14:24:20.157181787Z
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"scenario": "rolling replacement: migrate once, then add new replica, wait healthy, stop old one",
|
||||
"resources_under_load": [
|
||||
"messenger-lab3-api-10 cpu=49.91% mem=96.44MiB / 256MiB",
|
||||
"messenger-lab3-api-9 cpu=44.95% mem=113.9MiB / 256MiB",
|
||||
"messenger-lab3-lb-1 cpu=12.30% mem=17.51MiB / 64MiB",
|
||||
"messenger-lab3-postgres-1 cpu=23.73% mem=81.37MiB / 512MiB",
|
||||
"messenger-lab3-redis-1 cpu=5.40% mem=9.848MiB / 128MiB"
|
||||
],
|
||||
"before": [
|
||||
"/messenger-lab3-api-10 running image=f80c910ed3d1",
|
||||
"/messenger-lab3-api-9 running image=f80c910ed3d1"
|
||||
],
|
||||
"after": [
|
||||
"/messenger-lab3-api-11 running image=be7b642a4d66",
|
||||
"/messenger-lab3-api-12 running image=be7b642a4d66"
|
||||
],
|
||||
"steps": [
|
||||
{
|
||||
"replaced": "2701b0d53e0f",
|
||||
"new_replica_ready_seconds": 6.531,
|
||||
"step_seconds": 10.169
|
||||
},
|
||||
{
|
||||
"replaced": "75ad096eed0a",
|
||||
"new_replica_ready_seconds": 6.667,
|
||||
"step_seconds": 10.21
|
||||
}
|
||||
],
|
||||
"during_update": {
|
||||
"seconds": 30.809,
|
||||
"successful_writes": 5340,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 173.3,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.2,
|
||||
"p95": 73.5,
|
||||
"p99": 95.2
|
||||
},
|
||||
"max_write_gap_seconds": 0.17,
|
||||
"instances": [
|
||||
"18dde5d7e3c7",
|
||||
"2701b0d53e0f",
|
||||
"75ad096eed0a",
|
||||
"b446d5242566"
|
||||
]
|
||||
},
|
||||
"dataset": {
|
||||
"messages_in_db_before": 86799,
|
||||
"messages_in_db_after": 93308
|
||||
},
|
||||
"history": {
|
||||
"confirmed": 6509,
|
||||
"stored": 6509,
|
||||
"lost_confirmed": 0,
|
||||
"duplicates": 0
|
||||
},
|
||||
"load": {
|
||||
"workers": 4,
|
||||
"model": "closed loop, POST message",
|
||||
"warmup_seconds": 5,
|
||||
"client_timeout_seconds": 2,
|
||||
"retry": "same Idempotency-Key until success"
|
||||
},
|
||||
"date": "2026-11-01T14:27:40Z"
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# Публичные проверки через LB; разные реплики обслуживают одну сессию
|
||||
# date: 2026-11-01T14:24:16Z
|
||||
# commit: 210ff67 (dirty)
|
||||
|
||||
$ make check
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ make test
|
||||
python3 tests/smoke.py --base-url "http://lb:8080"
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
$ sh -c docker compose ps -q api | cut -c1-12
|
||||
2701b0d53e0f
|
||||
75ad096eed0a
|
||||
|
||||
$ python3 scripts/probe.py instances 6
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:24:18.673Z
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 75ad096eed0a
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 2701b0d53e0f
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 75ad096eed0a
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 2701b0d53e0f
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 75ad096eed0a
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 2701b0d53e0f
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# Собственные e2e-тесты (PostgreSQL + Redis из compose.test.yaml)
|
||||
# date: 2026-11-01T14:23:50Z
|
||||
# commit: 210ff67 (dirty)
|
||||
|
||||
$ docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose
|
||||
Network messenger-lab3-test_default Creating
|
||||
Network messenger-lab3-test_default Created
|
||||
Container messenger-lab3-test-redis-1 Creating
|
||||
Container messenger-lab3-test-postgres-1 Creating
|
||||
Container messenger-lab3-test-redis-1 Created
|
||||
Container messenger-lab3-test-postgres-1 Created
|
||||
Container messenger-lab3-test-postgres-1 Starting
|
||||
Container messenger-lab3-test-redis-1 Starting
|
||||
Container messenger-lab3-test-redis-1 Started
|
||||
Container messenger-lab3-test-postgres-1 Started
|
||||
Prisma schema loaded from prisma/schema.prisma
|
||||
Datasource "db": PostgreSQL database "messenger_test", schema "public" at "postgres:5432"
|
||||
|
||||
3 migrations found in prisma/migrations
|
||||
|
||||
Applying migration `20261021000000_init`
|
||||
Applying migration `20261021010000_auth_sessions`
|
||||
Applying migration `20261101000000_idempotency_keys`
|
||||
|
||||
The following migration(s) have been applied:
|
||||
|
||||
migrations/
|
||||
└─ 20261021000000_init/
|
||||
└─ migration.sql
|
||||
└─ 20261021010000_auth_sessions/
|
||||
└─ migration.sql
|
||||
└─ 20261101000000_idempotency_keys/
|
||||
└─ migration.sql
|
||||
|
||||
All migrations have been successfully applied.
|
||||
PASS test/docs.e2e-spec.ts (8.076 s)
|
||||
Swagger UI и примеры (e2e)
|
||||
✓ отдаёт Swagger UI и документ контракта со всеми путями (79 ms)
|
||||
✓ каждый пример запроса и ответа проходит JSON Schema контракта (458 ms)
|
||||
|
||||
PASS test/concurrency.e2e-spec.ts (9.302 s)
|
||||
Безопасность при конкурентном доступе (e2e)
|
||||
✓ принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных (1567 ms)
|
||||
✓ регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username (248 ms)
|
||||
|
||||
PASS test/auth.e2e-spec.ts (9.345 s)
|
||||
Аутентификация и сессии (e2e)
|
||||
регистрация
|
||||
✓ требует password (68 ms)
|
||||
✓ отклоняет password короче 12 code points (29 ms)
|
||||
✓ хранит пароль как Argon2id-хеш, а не открытым текстом (154 ms)
|
||||
POST /api/v1/auth/sessions
|
||||
✓ выдаёт непрозрачный Bearer-токен с expires_at и пользователем (298 ms)
|
||||
✓ принимает пароль с двоеточием и не-ASCII символами (81 ms)
|
||||
✓ отвечает одинаковым 401 на неверный пароль и неизвестного пользователя (452 ms)
|
||||
✓ отклоняет JSON body при входе даже с верным Basic (133 ms)
|
||||
✓ отвечает 401 без заголовка Authorization (13 ms)
|
||||
защищённые endpoint
|
||||
✓ не принимают Basic (126 ms)
|
||||
✓ не принимают X-User-Id сам по себе (114 ms)
|
||||
✓ игнорируют X-User-Id рядом с Bearer (219 ms)
|
||||
✓ отвечают 401 на неизвестный токен (13 ms)
|
||||
DELETE /api/v1/auth/sessions/current
|
||||
✓ отзывает только текущий токен: 204, затем 401 на повтор (211 ms)
|
||||
|
||||
PASS test/idempotency.e2e-spec.ts (11.29 s)
|
||||
Идемпотентность отправки и X-Instance-Id (e2e)
|
||||
✓ требует Idempotency-Key правильного формата (429 ms)
|
||||
✓ повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение (402 ms)
|
||||
✓ тот же ключ с другим телом — 409, сообщение не создаётся (586 ms)
|
||||
✓ 20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение (363 ms)
|
||||
✓ область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим (182 ms)
|
||||
✓ повтор заново проверяет сессию (94 ms)
|
||||
✓ после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново (1676 ms)
|
||||
✓ X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе (9 ms)
|
||||
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:24:12 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mDELETE /api/v1/auth/sessions/current -> 503: session cache unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:24:12 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mDELETE /api/v1/auth/sessions/current -> 503: session cache unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:24:13 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /health/ready -> 503: database unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:24:13 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /api/v1/chats -> 503: database unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:24:13 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /api/v1/chats -> 503: database unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:24:13 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mPOST /api/v1/users -> 503: database unavailable[39m
|
||||
PASS test/api.e2e-spec.ts (12.31 s)
|
||||
API мессенджера (e2e) — граничные случаи сверх публичного smoke
|
||||
POST /api/v1/users
|
||||
✓ отклоняет некорректный JSON с кодом 400 (75 ms)
|
||||
✓ отклоняет тело с лишними полями (26 ms)
|
||||
✓ отклоняет username с заглавными буквами (7 ms)
|
||||
✓ отклоняет display_name из одних пробелов (6 ms)
|
||||
✓ отклоняет дубликат username с кодом 409 (319 ms)
|
||||
✓ никогда не возвращает поле пароля или его хэша (57 ms)
|
||||
✓ отклоняет username короче 3 символов (6 ms)
|
||||
✓ отклоняет username длиннее 32 символов (6 ms)
|
||||
✓ отклоняет username с недопустимыми символами (дефис) (6 ms)
|
||||
✓ принимает username ровно на границах длины 3 и 32 символа (81 ms)
|
||||
✓ отклоняет display_name длиннее 100 Unicode code points (5 ms)
|
||||
✓ принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ (47 ms)
|
||||
✓ отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP (3 ms)
|
||||
контроль доступа
|
||||
✓ возвращает 401 раньше 404, если и актор, и ресурс невалидны (8 ms)
|
||||
✓ возвращает 404 (не 403), когда чат запрашивает не его участник (844 ms)
|
||||
✓ отклоняет создание чата, если вызывающий не входит в member_ids (267 ms)
|
||||
✓ отклоняет создание чата с дублирующимися member_ids (113 ms)
|
||||
✓ считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре (81 ms)
|
||||
✓ принимает ровно 100 участников и отклоняет 101 (108 ms)
|
||||
✓ отклоняет создание чата с неизвестным участником (81 ms)
|
||||
✓ отклоняет создание чата с пустым/пробельным title (77 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id (не UUID) (89 ms)
|
||||
✓ возвращает 404 для корректного по формату, но несуществующего chat_id (86 ms)
|
||||
GET /api/v1/chats (пагинация)
|
||||
✓ использует limit=50 по умолчанию, если limit не передан (83 ms)
|
||||
✓ отклоняет нечисловой limit (60 ms)
|
||||
✓ отклоняет limit=0 (65 ms)
|
||||
✓ отклоняет повторённые limit и cursor (67 ms)
|
||||
✓ отклоняет cursor, не являющийся корректным base64url JSON (65 ms)
|
||||
✓ отклоняет корректно закодированный cursor с id чата, который никогда не существовал (63 ms)
|
||||
✓ обходит весь список чатов по страницам без пропусков и дублей (102 ms)
|
||||
сообщения
|
||||
✓ не принимает sender_id, переданный клиентом (124 ms)
|
||||
✓ считает attachment_ids: [] равным отсутствию поля, непустой список отклоняет (145 ms)
|
||||
✓ отклоняет пустое сообщение (101 ms)
|
||||
✓ отклоняет сообщение из одних пробелов (114 ms)
|
||||
✓ отклоняет отправку в чат, где вызывающий не участник (158 ms)
|
||||
✓ отклоняет limit=0 при чтении истории (98 ms)
|
||||
✓ отклоняет limit=101 при чтении истории (115 ms)
|
||||
✓ отклоняет нечисловой limit (111 ms)
|
||||
✓ отклоняет текст сообщения длиннее 4000 Unicode code points (99 ms)
|
||||
✓ принимает текст сообщения ровно из 4000 Unicode code points (110 ms)
|
||||
✓ отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP (112 ms)
|
||||
✓ отклоняет cursor, не являющийся корректным base64url JSON (112 ms)
|
||||
✓ отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате (120 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id при отправке сообщения (47 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id при чтении истории (49 ms)
|
||||
✓ отклоняет cursor, взятый из другого чата (137 ms)
|
||||
✓ обходит всю историю по страницам без пропусков и дублей (158 ms)
|
||||
X-Request-Id
|
||||
✓ присутствует и уникален для независимых запросов (2 ms)
|
||||
✓ совпадает с request_id внутри тела ошибки (2 ms)
|
||||
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:24:13 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /api/v1/chats -> 500: Internal server error[39m
|
||||
PASS test/failures.e2e-spec.ts (12.501 s)
|
||||
Уровень 4: expiry, отказы зависимостей, rollback (e2e)
|
||||
✓ сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша (3629 ms)
|
||||
✓ без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва (162 ms)
|
||||
✓ logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше (343 ms)
|
||||
✓ без PostgreSQL отвечает ограниченным 503 и не пускает анонима (269 ms)
|
||||
✓ неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id (89 ms)
|
||||
✓ откатывает создание чата целиком, если один из участников не существует (105 ms)
|
||||
|
||||
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.
|
||||
Test Suites: 6 passed, 6 total
|
||||
Tests: 80 passed, 80 total
|
||||
Snapshots: 0 total
|
||||
Time: 13.518 s
|
||||
Ran all test suites.
|
||||
|
||||
Reference in New Issue
Block a user