forked from mtusi2026/mtusi2026lab3
lab3: проба готовности на отдельном соединении, серия роста на блоке why#
This commit is contained in:
+38
-14
@@ -28,7 +28,7 @@ src/
|
||||
cache/ версионированный кэш истории + lock на страницу
|
||||
idempotency/ журнал Idempotency-Key (claim/read/store/forget/GC)
|
||||
metrics/ /internal/metrics и /internal/metrics/reset
|
||||
health/ liveness/readiness с проверкой зависимостей + /internal/lb-check
|
||||
health/ liveness/readiness с проверкой зависимостей (readiness — проба LB)
|
||||
common/
|
||||
http/ cursor (формат+календарь), page (конверт {items,next_cursor}), request-id
|
||||
errors/ exception filter и тип тела ошибки ApiErrorBody
|
||||
@@ -102,6 +102,7 @@ npm run start:dev # или npm run start:prod после
|
||||
| `DATABASE_CONNECTION_TIMEOUT_MS` | `5000` | таймаут установки соединения |
|
||||
| `DATABASE_STATEMENT_TIMEOUT_MS` | `5000` | таймаут SQL-запроса |
|
||||
| `SESSION_TTL_SECONDS` | `3600` | TTL сессии (минимум 2) |
|
||||
| `HEALTH_TIMEOUT_MS` | `400` | бюджет проверки PostgreSQL/Redis внутри `/health/ready`; меньше `timeout check` HAProxy (500 ms) и `DATABASE_STATEMENT_TIMEOUT_MS` |
|
||||
| `CACHE_TTL_SECONDS` | `30` | TTL страницы истории в Redis |
|
||||
| `CACHE_MODE` | `protected` | `protected` (lock на страницу) или `naive` (только для эксперимента) |
|
||||
| `CACHE_LOCK_TTL_MS` | `1000` | TTL lock-а страницы |
|
||||
@@ -121,9 +122,8 @@ npm run start:dev # или npm run start:prod после
|
||||
|
||||
| Метод и путь | Аутентификация | Назначение |
|
||||
|---|---|---|
|
||||
| `GET /health/live` | нет | процесс жив |
|
||||
| `GET /health/ready` | нет | готовность: PostgreSQL и Redis доступны, иначе `503` |
|
||||
| `GET /internal/lb-check` | нет | проба балансировщика: только флаг дрейна, без обращения к БД/Redis |
|
||||
| `GET /health/live` | нет | процесс жив; не обращается к зависимостям, поэтому отвечает `200` и при их отказе |
|
||||
| `GET /health/ready` | нет | готовность реплики: флаг дреина + PostgreSQL и Redis (бюджет `HEALTH_TIMEOUT_MS`), иначе `503`; эту же ручку пробует HAProxy |
|
||||
| `POST /api/v1/users` | нет | регистрация с паролем (Argon2id) |
|
||||
| `POST /api/v1/auth/sessions` | `Basic` | вход, выдаёт opaque Bearer-токен |
|
||||
| `DELETE /api/v1/auth/sessions/current` | `Bearer` | отзыв текущей сессии, `204` |
|
||||
@@ -191,12 +191,30 @@ make test-dependencies
|
||||
Он включён по флагу `E2E_DEPENDENCY_FAULTS=1` (им же управляет цель Makefile),
|
||||
потому что требует прав на управление Docker Compose-проектом; остальные
|
||||
переменные — `E2E_COMPOSE_DIR`, `E2E_COMPOSE_ENV_FILE`, `E2E_REDIS_SERVICE`,
|
||||
`E2E_POSTGRES_SERVICE`. Проверяется для Redis и PostgreSQL: `/health/live`
|
||||
остаётся `200`, `/health/ready` и бизнес-запросы возвращают `503 unavailable`
|
||||
с `request_id` из `X-Request-Id` и без деталей драйвера, запрос без сессии —
|
||||
по-прежнему `401`, а после старта зависимости живы прежняя сессия,
|
||||
подтверждённое сообщение и новая запись. Каждый запрос к остановленной БД ждёт
|
||||
`DATABASE_CONNECTION_TIMEOUT_MS`, поэтому набор идёт около 40 секунд.
|
||||
`E2E_POSTGRES_SERVICE`, `E2E_API_SERVICE`, `E2E_LB_STATS_URL`,
|
||||
`E2E_POSTGRES_USER`, `E2E_POSTGRES_DB`, `E2E_PG_HBA_PATH`.
|
||||
|
||||
Проверяются три топологии отказа:
|
||||
|
||||
1. **Отказ Redis** (общая зависимость): `/health/live` реплики остаётся `200`,
|
||||
`/health/ready` и бизнес-запросы — `503 unavailable` с `request_id` из
|
||||
`X-Request-Id` и без деталей драйвера, запрос без сессии — по-прежнему `401`.
|
||||
Неготовыми становятся все реплики, HAProxy исключает их из ротации и
|
||||
отвечает собственным `503`; после старта Redis сессия и подтверждённое
|
||||
сообщение живы.
|
||||
2. **Отказ PostgreSQL** (общая зависимость): то же плюс проверка, что после
|
||||
возврата зависимости данные на месте и новая запись проходит.
|
||||
3. **Отказ PostgreSQL у одной реплики** (локальный путь к БД): для адреса
|
||||
выбранной реплики временно ставится `reject`-строка в `pg_hba.conf` (первое
|
||||
совпадение) и обрываются её соединения. Выбранная реплика отвечает `503` и её
|
||||
слот уходит в `DOWN`, здоровая продолжает `200`/`UP` и обслуживает все чтения
|
||||
через LB; `pg_hba.conf` восстанавливается в `finally`, после чего реплика
|
||||
возвращается в ротацию и снова получает запросы.
|
||||
|
||||
Реплики API портов не публикуют, поэтому отдельная реплика опрашивается изнутри
|
||||
своего контейнера (loopback), а состояние слотов — из `stats;csv` HAProxy
|
||||
(`127.0.0.1:8404`). Каждый запрос к остановленной БД ждёт
|
||||
`DATABASE_CONNECTION_TIMEOUT_MS`, поэтому набор идёт около минуты.
|
||||
|
||||
## Реплики, балансировка и остановка реплики
|
||||
|
||||
@@ -224,10 +242,16 @@ scripts/start-replica.sh # вернуть остано
|
||||
пулов раньше `beforeApplicationShutdown`), реплика какое-то время остаётся в
|
||||
ротации уже без ресурсов — это и было причиной явной последовательности в
|
||||
`src/main.ts`.
|
||||
- `/internal/lb-check` намеренно не проверяет БД и Redis: отказ общей
|
||||
зависимости нельзя исправить выводом реплик из ротации, иначе LB ответит
|
||||
клиенту своей HTML-страницей вместо ограниченного `503 unavailable`.
|
||||
`/health/ready` остаётся операторским сигналом и healthcheck'ом контейнера.
|
||||
- **Проба LB — тот же `/health/ready`**, что и healthcheck контейнера: реплика,
|
||||
потерявшая обязательную зависимость (свой путь к PostgreSQL или Redis),
|
||||
выходит из ротации, и трафик уходит на здоровые реплики. Проба с зависимостями
|
||||
ограничена `HEALTH_TIMEOUT_MS=400` на реплику (per-query `query_timeout` для
|
||||
`SELECT 1` и `AbortSignal.timeout` для `PING`), поэтому она укладывается в
|
||||
`timeout check 500ms` HAProxy. Когда недоступна общая для всех зависимость,
|
||||
неготовыми становятся все реплики, и клиент получает `503` от самого LB: это
|
||||
честный ответ «готовых узлов нет» вместо маскировки отказа.
|
||||
- `/health/live` зависимостей не касается: он отвечает `200`, пока жив процесс,
|
||||
и по нему проверяют, что реплика не упала (в том числе при отказе PG/Redis).
|
||||
|
||||
## Идемпотентность отправки сообщения
|
||||
|
||||
|
||||
@@ -48,6 +48,9 @@ export const appConfigSchema = z
|
||||
undefined,
|
||||
5000,
|
||||
),
|
||||
// Бюджет зависимостей в /health/ready: LB проверяет ту же ручку, поэтому
|
||||
// проба готовности обязана уложиться в timeout check HAProxy (500 ms).
|
||||
HEALTH_TIMEOUT_MS: numeric('HEALTH_TIMEOUT_MS', 1, undefined, 400),
|
||||
CACHE_TTL_SECONDS: numeric('CACHE_TTL_SECONDS', 1, undefined, 30),
|
||||
CACHE_MODE: z.enum(['protected', 'naive']).default('protected'),
|
||||
CACHE_LOCK_TTL_MS: numeric('CACHE_LOCK_TTL_MS', 1, undefined, 1000),
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { AppConfig } from '../config/app-config.schema.js';
|
||||
@Injectable()
|
||||
export class DatabaseClient implements OnModuleDestroy {
|
||||
readonly pool: pg.Pool;
|
||||
private readonly healthPool: pg.Pool;
|
||||
private readonly logger = new Logger(DatabaseClient.name);
|
||||
|
||||
constructor(
|
||||
@@ -29,6 +30,19 @@ export class DatabaseClient implements OnModuleDestroy {
|
||||
this.metrics.increment('database.pool_error');
|
||||
this.logger.warn(`PostgreSQL pool error: ${error.message}`);
|
||||
});
|
||||
// Проба готовности не должна стоять в очереди за бизнес-запросами: занятый
|
||||
// общий пул — это перегрузка, а не потеря зависимости.
|
||||
this.healthPool = new pg.Pool({
|
||||
connectionString: this.config.getOrThrow('DATABASE_URL'),
|
||||
max: 1,
|
||||
idleTimeoutMillis: 0,
|
||||
connectionTimeoutMillis: this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
|
||||
query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
|
||||
});
|
||||
this.healthPool.on('error', (error: Error) => {
|
||||
this.metrics.increment('database.health_pool_error');
|
||||
this.logger.warn(`PostgreSQL health connection error: ${error.message}`);
|
||||
});
|
||||
}
|
||||
|
||||
query<T extends pg.QueryResultRow = pg.QueryResultRow>(
|
||||
@@ -41,7 +55,8 @@ export class DatabaseClient implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
async health(): Promise<void> {
|
||||
await this.query('health.database', 'SELECT 1');
|
||||
this.metrics.increment('health.database');
|
||||
await this.healthPool.query('SELECT 1');
|
||||
}
|
||||
|
||||
async withTransaction<T>(
|
||||
@@ -70,6 +85,6 @@ export class DatabaseClient implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.pool.end();
|
||||
await Promise.all([this.pool.end(), this.healthPool.end()]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller.js';
|
||||
import { LbCheckController } from './lb-check.controller.js';
|
||||
import { HealthService } from './health.service.js';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, RedisModule],
|
||||
controllers: [HealthController, LbCheckController],
|
||||
controllers: [HealthController],
|
||||
providers: [HealthService],
|
||||
})
|
||||
export class HealthModule {}
|
||||
|
||||
@@ -9,6 +9,7 @@ describe('HealthService', () => {
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
expect(service.getLiveness()).toEqual({ status: 'ok' });
|
||||
await expect(service.getReadiness()).resolves.toEqual({ status: 'ok' });
|
||||
@@ -22,6 +23,22 @@ describe('HealthService', () => {
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
await expect(service.getReadiness()).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects readiness when Redis alone is unavailable', async () => {
|
||||
const database = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const redis = {
|
||||
health: vi.fn().mockRejectedValue(new Error('down')),
|
||||
};
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
await expect(service.getReadiness()).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException,
|
||||
@@ -32,6 +49,7 @@ describe('HealthService', () => {
|
||||
const service = new HealthService(
|
||||
{ health: vi.fn() } as never,
|
||||
{ health: vi.fn() } as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
service.setDraining();
|
||||
expect(service.getLiveness()).toEqual({ status: 'ok' });
|
||||
@@ -40,13 +58,34 @@ describe('HealthService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the load-balancer check positive while a dependency is down', async () => {
|
||||
it('answers not-ready during drain without probing dependencies', async () => {
|
||||
const database = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const redis = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const service = new HealthService(
|
||||
{ health: vi.fn().mockRejectedValue(new Error('down')) } as never,
|
||||
{ health: vi.fn().mockRejectedValue(new Error('down')) } as never,
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
expect(service.getLbCheck()).toEqual({ status: 'ok' });
|
||||
service.setDraining();
|
||||
expect(() => service.getLbCheck()).toThrow('Draining');
|
||||
await expect(service.getReadiness()).rejects.toThrow(
|
||||
'Service is shutting down',
|
||||
);
|
||||
// Дрейн обязан отвечать сразу: проба LB не должна ждать зависимости,
|
||||
// когда реплика уже выходит из ротации.
|
||||
expect(database.health).not.toHaveBeenCalled();
|
||||
expect(redis.health).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails readiness within the budget when a dependency hangs', async () => {
|
||||
const database = { health: vi.fn(() => new Promise<void>(() => {})) };
|
||||
const redis = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 20 } as never,
|
||||
);
|
||||
await expect(service.getReadiness()).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import { RedisClient } from '../redis/redis.client.js';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
|
||||
@Injectable()
|
||||
export class HealthService {
|
||||
@@ -13,34 +15,41 @@ export class HealthService {
|
||||
constructor(
|
||||
private readonly database: DatabaseClient,
|
||||
private readonly redis: RedisClient,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
) {}
|
||||
getLiveness() {
|
||||
return { status: 'ok' as const };
|
||||
}
|
||||
// Load-balancer probe, deliberately independent of PostgreSQL and Redis: a
|
||||
// shared dependency outage cannot be fixed by removing replicas from
|
||||
// rotation, and draining every backend would answer clients with the LB's
|
||||
// own HTML error page instead of the bounded API 503. /health/ready stays
|
||||
// the operator-facing readiness signal.
|
||||
getLbCheck() {
|
||||
if (!this.ready)
|
||||
throw new ServiceUnavailableException('Draining');
|
||||
return { status: 'ok' as const };
|
||||
}
|
||||
async getReadiness() {
|
||||
if (!this.ready)
|
||||
throw new ServiceUnavailableException('Service is shutting down');
|
||||
const dependencies = Promise.all([
|
||||
this.database.health(),
|
||||
this.redis.health(),
|
||||
]);
|
||||
// Поздний отказ после дедлайна не должен стать unhandled rejection.
|
||||
dependencies.catch(() => undefined);
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const deadline = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() => reject(new Error('readiness budget exceeded')),
|
||||
this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
|
||||
);
|
||||
});
|
||||
try {
|
||||
await Promise.all([this.database.health(), this.redis.health()]);
|
||||
await Promise.race([dependencies, deadline]);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('Dependencies unavailable');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
return { status: 'ok' as const };
|
||||
}
|
||||
// Called on SIGTERM before the drain delay: the replica turns not-ready for
|
||||
// both the LB probe and the operator probe while it finishes in-flight
|
||||
// requests. The delay itself lives in main.ts, because Nest destroys
|
||||
// providers (closing the pools) before this class could serve anyone.
|
||||
// Called on SIGTERM before the drain delay: the replica turns not-ready while
|
||||
// it finishes in-flight requests, so the load balancer stops probing it
|
||||
// successfully and removes it from rotation. The delay itself lives in
|
||||
// main.ts, because Nest destroys providers (closing the pools) before this
|
||||
// class could serve anyone.
|
||||
setDraining() {
|
||||
this.ready = false;
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { HealthService } from './health.service.js';
|
||||
|
||||
// The load balancer probes this route instead of /health/ready so that a shared
|
||||
// database outage cannot drain the whole fleet; see HealthService.getLbCheck.
|
||||
@Controller('internal')
|
||||
export class LbCheckController {
|
||||
constructor(private readonly health: HealthService) {}
|
||||
|
||||
@Get('lb-check')
|
||||
check() {
|
||||
return this.health.getLbCheck();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createClient, type RedisClientType } from 'redis';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
@@ -43,7 +48,13 @@ export class RedisClient implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
async health(): Promise<void> {
|
||||
this.metrics.increment('redis.ping');
|
||||
await this.client.ping();
|
||||
// AbortSignal.timeout ограничивает именно пробу: обычные GET/SET остаются
|
||||
// без командного таймаута, а замороженный Redis проваливает готовность
|
||||
// в бюджет, который короче timeout check балансировщика.
|
||||
const timeout = AbortSignal.timeout(
|
||||
this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
|
||||
);
|
||||
await this.client.withAbortSignal(timeout).ping();
|
||||
}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
|
||||
@@ -11,10 +11,20 @@ import type { Page } from '../src/common/http/page.js';
|
||||
import type { Message } from '../src/messages/message.js';
|
||||
import type { User } from '../src/users/user.js';
|
||||
|
||||
// Automated counterpart of the manual Redis/PostgreSQL outage checks: the suite
|
||||
// stops a dependency of the Compose stand, asserts a bounded 503 (never a 500,
|
||||
// never a trusted anonymous request, never a leaked driver error) and then
|
||||
// restarts it to prove recovery without data loss.
|
||||
// Automated counterpart of the manual Redis/PostgreSQL outage checks. Four
|
||||
// topologies, because the load balancer probes /health/ready (the same route as
|
||||
// the container healthcheck):
|
||||
// 1. Redis outage — shared dependency: every replica turns not-ready, HAProxy
|
||||
// removes all backends and answers 503 itself, while the replica's own
|
||||
// readiness stays a bounded API 503 with request_id.
|
||||
// 2. PostgreSQL outage — same shared-dependency topology, confirmed data and
|
||||
// the session survive the restart.
|
||||
// 3. Per-replica PostgreSQL fault — only the selected replica loses its own
|
||||
// path to the database (temporary pg_hba reject entry for its address plus
|
||||
// connection termination): that slot leaves rotation, the healthy replica
|
||||
// keeps serving, and the fault is always undone.
|
||||
// 4. Pool saturation — a busy shared pool is overload, not a lost dependency:
|
||||
// the replicas stay in rotation because the probe uses its own connection.
|
||||
//
|
||||
// It is opt-in because it needs control over the Docker Compose project:
|
||||
// make test-dependencies
|
||||
@@ -30,22 +40,52 @@ const composeDir =
|
||||
const composeEnvFile = process.env.E2E_COMPOSE_ENV_FILE ?? '.env';
|
||||
const redisService = process.env.E2E_REDIS_SERVICE ?? 'redis';
|
||||
const postgresService = process.env.E2E_POSTGRES_SERVICE ?? 'postgres';
|
||||
const apiService = process.env.E2E_API_SERVICE ?? 'api';
|
||||
const lbStatsUrl =
|
||||
process.env.E2E_LB_STATS_URL ?? 'http://127.0.0.1:8404/stats;csv';
|
||||
// PostgreSQL superuser of the stand (compose.yaml, .env); psql runs over the
|
||||
// container's local socket, so no password is needed here.
|
||||
const postgresUser = process.env.E2E_POSTGRES_USER ?? 'messenger';
|
||||
const postgresDatabase = process.env.E2E_POSTGRES_DB ?? 'messenger';
|
||||
const pgHbaPath =
|
||||
process.env.E2E_PG_HBA_PATH ?? '/var/lib/postgresql/data/pg_hba.conf';
|
||||
const pgHbaBackup = `${pgHbaPath}.lab3-partial-fault.bak`;
|
||||
const password = 'outage-check:пароль🔐';
|
||||
const runId = randomUUID().replaceAll('-', '').slice(0, 12);
|
||||
// A request that reaches a stopped database waits for the pool connection
|
||||
// timeout, so every outage step costs up to DATABASE_CONNECTION_TIMEOUT_MS.
|
||||
const outagedRequestBudgetMs = 180_000;
|
||||
const slotBudgetMs = 20_000;
|
||||
// Rotation is checked with HTTP reads through the LB, not with check counters.
|
||||
const readyReads = 16;
|
||||
const saturatingWrites = 60; // больше, чем replicas × DATABASE_POOL_MAX (2 × 10)
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
type Result<T> = { body: T; text: string; response: Response };
|
||||
type ReplicaProbe = {
|
||||
instanceId: string | null;
|
||||
requestId: string | null;
|
||||
status: number;
|
||||
text: string;
|
||||
};
|
||||
type LbSlot = { addr: string; check: string; name: string; status: string };
|
||||
|
||||
async function compose(...args: string[]): Promise<void> {
|
||||
await execFileAsync(
|
||||
async function compose(...args: string[]): Promise<string> {
|
||||
const result = await execFileAsync(
|
||||
'docker',
|
||||
['compose', '--env-file', composeEnvFile, ...args],
|
||||
{ cwd: composeDir, timeout: 120_000 },
|
||||
);
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
async function docker(...args: string[]): Promise<string> {
|
||||
const result = await execFileAsync('docker', args, {
|
||||
cwd: composeDir,
|
||||
timeout: 60_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
async function request<T = unknown>(
|
||||
@@ -54,7 +94,15 @@ async function request<T = unknown>(
|
||||
): Promise<Result<T>> {
|
||||
const response = await fetch(`${baseUrl}${path}`, init);
|
||||
const text = await response.text();
|
||||
return { body: (text ? JSON.parse(text) : undefined) as T, text, response };
|
||||
// With every backend out of rotation the answer is the LB's own HTML 503,
|
||||
// so a body is not guaranteed to be JSON (it always is for API answers).
|
||||
let body: T | undefined;
|
||||
try {
|
||||
body = text ? (JSON.parse(text) as T) : undefined;
|
||||
} catch {
|
||||
body = undefined;
|
||||
}
|
||||
return { body: body as T, text, response };
|
||||
}
|
||||
|
||||
function json(
|
||||
@@ -109,26 +157,290 @@ async function waitForReadiness(
|
||||
}
|
||||
}
|
||||
|
||||
function expectBoundedOutage(result: Result<ApiErrorBody>): void {
|
||||
expect(result.response.status).toBe(503);
|
||||
expect(result.body.error.code).toBe('unavailable');
|
||||
expect(result.body.error.message).toBe('Service unavailable');
|
||||
expect(result.body.error.request_id).toBe(
|
||||
result.response.headers.get('x-request-id'),
|
||||
);
|
||||
async function waitFor(
|
||||
condition: () => Promise<boolean>,
|
||||
describe: () => Promise<string>,
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
if (await condition()) return;
|
||||
if (Date.now() > deadline)
|
||||
throw new Error(
|
||||
`condition not reached within ${timeoutMs}ms: ${await describe()}`,
|
||||
);
|
||||
await sleep(250);
|
||||
}
|
||||
}
|
||||
|
||||
// Contract of the bounded unavailable error, checked both on the API replica
|
||||
// (JSON body with request_id) and through the load balancer.
|
||||
function expectBoundedError(
|
||||
status: number,
|
||||
text: string,
|
||||
requestId: string | null,
|
||||
): void {
|
||||
expect(status).toBe(503);
|
||||
const body = JSON.parse(text) as ApiErrorBody;
|
||||
expect(body.error.code).toBe('unavailable');
|
||||
expect(body.error.message).toBe('Service unavailable');
|
||||
expect(body.error.request_id).toBe(requestId);
|
||||
// A bounded error must not leak driver details, SQL text or a stack trace.
|
||||
expect(result.text).not.toMatch(
|
||||
expect(text).not.toMatch(
|
||||
/ECONNREFUSED|ECONNRESET|Connection terminated|pg\.|node_modules|at .*\(.+:\d+:\d+\)/u,
|
||||
);
|
||||
}
|
||||
|
||||
function expectBoundedOutage(result: Result<ApiErrorBody>): void {
|
||||
expectBoundedError(
|
||||
result.response.status,
|
||||
result.text,
|
||||
result.response.headers.get('x-request-id'),
|
||||
);
|
||||
}
|
||||
|
||||
// With every backend out of rotation the last hop is the load balancer itself:
|
||||
// it answers with its own 503 page, so there is no API error body and no
|
||||
// X-Instance-Id — the request never reached a replica.
|
||||
function expectLbOutage(result: Result<unknown>): void {
|
||||
expect(result.response.status).toBe(503);
|
||||
expect(result.response.headers.get('x-instance-id')).toBeNull();
|
||||
}
|
||||
|
||||
// What a client sees while a shared dependency is down: either the bounded 503
|
||||
// of a replica that is still in rotation (identified by X-Instance-Id), or the
|
||||
// LB's own 503 once every replica has left rotation. Never a success.
|
||||
function expectUnavailableThroughLb(result: Result<ApiErrorBody>): void {
|
||||
expect(result.response.status).toBe(503);
|
||||
if (result.response.headers.get('x-instance-id') === null) return;
|
||||
expectBoundedOutage(result);
|
||||
}
|
||||
|
||||
async function historyOf(
|
||||
chatId: string,
|
||||
token: string,
|
||||
): Promise<Result<Page<Message>>> {
|
||||
return request<Page<Message>>(`/api/v1/chats/${chatId}/messages?limit=100`, {
|
||||
headers: bearer(token),
|
||||
});
|
||||
return request<Page<Message>>(
|
||||
`/api/v1/chats/${chatId}/messages?limit=100`,
|
||||
{
|
||||
headers: bearer(token),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function apiContainers(): Promise<string[]> {
|
||||
const stdout = await compose('ps', '-q', apiService);
|
||||
return stdout
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.sort();
|
||||
}
|
||||
|
||||
async function containerIp(container: string): Promise<string> {
|
||||
return docker(
|
||||
'inspect',
|
||||
'-f',
|
||||
'{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}',
|
||||
container,
|
||||
);
|
||||
}
|
||||
|
||||
// The replicas publish no ports, so a single replica is probed from inside its
|
||||
// own network namespace (loopback).
|
||||
const probeScript = `
|
||||
const params = JSON.parse(process.env.LAB3_PROBE);
|
||||
const port = process.env.APP_PORT || 8080;
|
||||
const response = await fetch('http://127.0.0.1:' + port + params.path, {
|
||||
method: params.method || 'GET',
|
||||
headers: params.headers || {},
|
||||
body: params.body,
|
||||
});
|
||||
const text = await response.text();
|
||||
console.log(JSON.stringify({
|
||||
status: response.status,
|
||||
text,
|
||||
instanceId: response.headers.get('x-instance-id'),
|
||||
requestId: response.headers.get('x-request-id'),
|
||||
}));
|
||||
`;
|
||||
|
||||
type ProbeInit = {
|
||||
body?: string;
|
||||
headers?: Record<string, string>;
|
||||
method?: string;
|
||||
};
|
||||
|
||||
async function probeReplica(
|
||||
container: string,
|
||||
path: string,
|
||||
init: ProbeInit = {},
|
||||
): Promise<ReplicaProbe> {
|
||||
const stdout = await docker(
|
||||
'exec',
|
||||
'-e',
|
||||
`LAB3_PROBE=${JSON.stringify({ path, ...init })}`,
|
||||
container,
|
||||
'node',
|
||||
'--input-type=module',
|
||||
'-e',
|
||||
probeScript,
|
||||
);
|
||||
return JSON.parse(stdout) as ReplicaProbe;
|
||||
}
|
||||
|
||||
async function waitForReplicaReadiness(
|
||||
container: string,
|
||||
expected: number,
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
let last = 'no probe';
|
||||
await waitFor(
|
||||
async () => {
|
||||
try {
|
||||
const probe = await probeReplica(container, '/health/ready');
|
||||
last = `${probe.status} ${probe.text}`;
|
||||
return probe.status === expected;
|
||||
} catch (error) {
|
||||
last = error instanceof Error ? error.message : 'probe failed';
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async () => last,
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
function parseCsvLine(line: string): string[] {
|
||||
const values: string[] = [];
|
||||
let current = '';
|
||||
let quoted = false;
|
||||
for (const character of line) {
|
||||
if (character === '"') quoted = !quoted;
|
||||
else if (character === ',' && !quoted) {
|
||||
values.push(current);
|
||||
current = '';
|
||||
} else current += character;
|
||||
}
|
||||
values.push(current.replace(/\r$/u, ''));
|
||||
return values;
|
||||
}
|
||||
|
||||
// Resolved backend slots of the api backend: the unused slots of the
|
||||
// server-template have no address and are ignored.
|
||||
async function lbSlots(): Promise<LbSlot[]> {
|
||||
const response = await fetch(lbStatsUrl);
|
||||
const lines = (await response.text()).trim().split('\n');
|
||||
const header = parseCsvLine(lines[0].replace(/^#\s*/u, '')).map((name) =>
|
||||
name.trim(),
|
||||
);
|
||||
const column = (name: string): number => header.indexOf(name);
|
||||
return lines
|
||||
.slice(1)
|
||||
.map(parseCsvLine)
|
||||
.filter(
|
||||
(columns) =>
|
||||
columns[column('pxname')] === 'api' &&
|
||||
/^api\d+$/u.test(columns[column('svname')] ?? '') &&
|
||||
(columns[column('addr')] ?? '').length > 0,
|
||||
)
|
||||
.map((columns) => ({
|
||||
addr: columns[column('addr')],
|
||||
check: columns[column('check_status')],
|
||||
name: columns[column('svname')],
|
||||
status: columns[column('status')],
|
||||
}));
|
||||
}
|
||||
|
||||
async function waitForSlot(
|
||||
predicate: (slots: LbSlot[]) => boolean,
|
||||
describe: string,
|
||||
timeoutMs = slotBudgetMs,
|
||||
): Promise<LbSlot[]> {
|
||||
let last = 'no stats';
|
||||
await waitFor(
|
||||
async () => {
|
||||
try {
|
||||
const slots = await lbSlots();
|
||||
last = slots
|
||||
.map(
|
||||
(slot) =>
|
||||
`${slot.name}@${slot.addr} ${slot.status}/${slot.check}`,
|
||||
)
|
||||
.join(', ');
|
||||
return slots.length > 0 && predicate(slots);
|
||||
} catch (error) {
|
||||
last = error instanceof Error ? error.message : 'stats failed';
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async () => `${describe} (last: ${last})`,
|
||||
timeoutMs,
|
||||
);
|
||||
return lbSlots();
|
||||
}
|
||||
|
||||
function upSlots(slots: LbSlot[]): LbSlot[] {
|
||||
return slots.filter((slot) => slot.status === 'UP');
|
||||
}
|
||||
|
||||
async function psql(query: string): Promise<string> {
|
||||
return dockerExecService(
|
||||
postgresService,
|
||||
'psql',
|
||||
'-U',
|
||||
postgresUser,
|
||||
'-d',
|
||||
postgresDatabase,
|
||||
'-tA',
|
||||
'-c',
|
||||
query,
|
||||
);
|
||||
}
|
||||
|
||||
// docker exec needs a container, while the suite is configured with Compose
|
||||
// service names, so the container of the service is resolved first.
|
||||
async function dockerExecService(
|
||||
service: string,
|
||||
...args: string[]
|
||||
): Promise<string> {
|
||||
const container = (await compose('ps', '-q', service))
|
||||
.split('\n')[0]
|
||||
?.trim();
|
||||
if (!container) throw new Error(`no container for service ${service}`);
|
||||
return docker('exec', container, ...args);
|
||||
}
|
||||
|
||||
// Takes away the replica's own path to PostgreSQL without touching the shared
|
||||
// database: a reject entry for the replica's address becomes the first matching
|
||||
// line of pg_hba.conf, so its new connections fail while the server stays up
|
||||
// for everyone else. The file is rewritten through the existing inode (`cat >
|
||||
// file`) to preserve the owner and mode the server needs to reload it.
|
||||
async function applyReplicaDatabaseReject(address: string): Promise<void> {
|
||||
const script = [
|
||||
`test -f ${pgHbaBackup} || cat ${pgHbaPath} > ${pgHbaBackup}`,
|
||||
`printf 'host all all ${address}/32 reject\\n' > /tmp/lab3-pg-hba`,
|
||||
`cat ${pgHbaPath} >> /tmp/lab3-pg-hba`,
|
||||
`cat /tmp/lab3-pg-hba > ${pgHbaPath}`,
|
||||
'rm -f /tmp/lab3-pg-hba',
|
||||
].join('; ');
|
||||
await dockerExecService(postgresService, 'sh', '-c', script);
|
||||
await psql('select pg_reload_conf()');
|
||||
await psql(
|
||||
`select count(pg_terminate_backend(pid)) from pg_stat_activity where client_addr = '${address}'`,
|
||||
);
|
||||
}
|
||||
|
||||
// Idempotent restore: also runs from afterAll, so an assertion that failed
|
||||
// mid-fault cannot leave the stand rejecting one replica.
|
||||
async function restoreDatabaseAccess(): Promise<void> {
|
||||
await dockerExecService(
|
||||
postgresService,
|
||||
'sh',
|
||||
'-c',
|
||||
`if [ -f ${pgHbaBackup} ]; then cat ${pgHbaBackup} > ${pgHbaPath}; rm -f ${pgHbaBackup}; fi`,
|
||||
);
|
||||
await psql('select pg_reload_conf()');
|
||||
}
|
||||
|
||||
describe.skipIf(!enabled)('dependency outages', () => {
|
||||
@@ -136,6 +448,7 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
let token: string;
|
||||
let chat: Chat;
|
||||
let message: Message;
|
||||
let replicas: string[];
|
||||
|
||||
beforeAll(async () => {
|
||||
await compose('up', '-d');
|
||||
@@ -171,49 +484,129 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
message = sent.body;
|
||||
replicas = await apiContainers();
|
||||
// Partial removal from rotation needs a healthy peer to compare with.
|
||||
expect(replicas.length).toBeGreaterThanOrEqual(2);
|
||||
await waitForSlot(
|
||||
(slots) => upSlots(slots).length === replicas.length,
|
||||
'not every replica is UP',
|
||||
30_000,
|
||||
);
|
||||
}, outagedRequestBudgetMs);
|
||||
|
||||
afterAll(async () => {
|
||||
// Always restore the stand, even when an assertion failed mid-outage.
|
||||
// Always restore the stand, even when an assertion failed mid-outage:
|
||||
// first the services (pg_hba is only reachable in a running container),
|
||||
// then the temporary per-replica rule, then rotation.
|
||||
await compose('start', redisService);
|
||||
await compose('start', postgresService);
|
||||
await waitForReadiness(200);
|
||||
await restoreDatabaseAccess();
|
||||
const expected = (await apiContainers()).length;
|
||||
await waitForSlot(
|
||||
(slots) => upSlots(slots).length === expected,
|
||||
'backends did not return to rotation',
|
||||
30_000,
|
||||
);
|
||||
}, outagedRequestBudgetMs);
|
||||
|
||||
it(
|
||||
'keeps every replica in rotation while the database pool is saturated',
|
||||
async () => {
|
||||
// A row lock on the chat parks every write in the shared pool; the
|
||||
// readiness probe uses its own connection and must keep answering.
|
||||
const lock = psql(
|
||||
`begin; select id from chats where id = '${chat.id}' for update; select pg_sleep(4); commit;`,
|
||||
);
|
||||
await sleep(300);
|
||||
const statuses = new Set<string>();
|
||||
let sampling = true;
|
||||
const sampler = (async () => {
|
||||
while (sampling) {
|
||||
for (const slot of await lbSlots()) statuses.add(slot.status);
|
||||
await sleep(200);
|
||||
}
|
||||
})();
|
||||
const writes = await Promise.all(
|
||||
Array.from({ length: saturatingWrites }, () =>
|
||||
request(
|
||||
`/api/v1/chats/${chat.id}/messages`,
|
||||
json({ text: 'saturation' }, messageHeaders(token)),
|
||||
),
|
||||
),
|
||||
);
|
||||
await lock;
|
||||
await sleep(1000);
|
||||
sampling = false;
|
||||
await sampler;
|
||||
expect([...statuses]).toEqual(['UP']);
|
||||
expect(
|
||||
writes
|
||||
.map((write) => write.response.status)
|
||||
.filter((status) => status !== 201),
|
||||
).toEqual([]);
|
||||
},
|
||||
outagedRequestBudgetMs,
|
||||
);
|
||||
|
||||
it(
|
||||
'serves bounded 503 for the Redis outage and recovers the session',
|
||||
async () => {
|
||||
await compose('stop', redisService);
|
||||
const replica = replicas[0];
|
||||
|
||||
const live = await request('/health/live');
|
||||
expect(live.response.status).toBe(200);
|
||||
await waitForReadiness(503);
|
||||
// The replica itself stays bounded: liveness is unaffected, readiness
|
||||
// and business requests report the missing dependency with an API
|
||||
// error body.
|
||||
expect((await probeReplica(replica, '/health/live')).status).toBe(
|
||||
200,
|
||||
);
|
||||
await waitForReplicaReadiness(replica, 503, 30_000);
|
||||
const readiness = await probeReplica(replica, '/health/ready');
|
||||
expectBoundedError(
|
||||
readiness.status,
|
||||
readiness.text,
|
||||
readiness.requestId,
|
||||
);
|
||||
|
||||
expectBoundedOutage(await request<ApiErrorBody>('/health/ready'));
|
||||
const me = await probeReplica(replica, '/api/v1/users/me', {
|
||||
headers: bearer(token),
|
||||
});
|
||||
expectBoundedError(me.status, me.text, me.requestId);
|
||||
|
||||
expectBoundedOutage(
|
||||
// A request without a session must stay unauthorized during an outage:
|
||||
// the outage may not turn an anonymous caller into a trusted one.
|
||||
const anonymous = await probeReplica(replica, '/api/v1/chats', {
|
||||
headers: { 'x-user-id': user.id },
|
||||
});
|
||||
expect(anonymous.status).toBe(401);
|
||||
expect(
|
||||
(JSON.parse(anonymous.text) as ApiErrorBody).error.code,
|
||||
).toBe('unauthorized');
|
||||
|
||||
// The shared dependency is missing for every replica: a client keeps
|
||||
// getting 503 (from a replica first, then from the LB itself), and
|
||||
// once all backends have left rotation the answer is the LB's own.
|
||||
expectUnavailableThroughLb(
|
||||
await request<ApiErrorBody>('/api/v1/users/me', {
|
||||
headers: bearer(token),
|
||||
}),
|
||||
);
|
||||
|
||||
expectBoundedOutage(
|
||||
await request<ApiErrorBody>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: { authorization: basic(user.username, password) },
|
||||
}),
|
||||
await waitForSlot(
|
||||
(slots) => upSlots(slots).length === 0,
|
||||
'not every slot left rotation',
|
||||
);
|
||||
expectLbOutage(
|
||||
await request('/api/v1/users/me', { headers: bearer(token) }),
|
||||
);
|
||||
|
||||
// A request without a session must stay unauthorized during an outage:
|
||||
// the outage may not turn an anonymous caller into a trusted one.
|
||||
const anonymous = await request<ApiErrorBody>('/api/v1/chats', {
|
||||
headers: { 'x-user-id': user.id },
|
||||
});
|
||||
expect(anonymous.response.status).toBe(401);
|
||||
expect(anonymous.body.error.code).toBe('unauthorized');
|
||||
|
||||
await compose('start', redisService);
|
||||
await waitForReadiness(200);
|
||||
await waitForSlot(
|
||||
(slots) => upSlots(slots).length === replicas.length,
|
||||
'backends did not return to rotation',
|
||||
30_000,
|
||||
);
|
||||
|
||||
// Sessions live in Redis with persistence, so the old token still works.
|
||||
const recovered = await request<User>('/api/v1/users/me', {
|
||||
@@ -235,46 +628,75 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
'serves bounded 503 for the PostgreSQL outage and keeps confirmed data',
|
||||
async () => {
|
||||
await compose('stop', postgresService);
|
||||
const replica = replicas[0];
|
||||
|
||||
const live = await request('/health/live');
|
||||
expect(live.response.status).toBe(200);
|
||||
await waitForReadiness(503);
|
||||
expect((await probeReplica(replica, '/health/live')).status).toBe(
|
||||
200,
|
||||
);
|
||||
await waitForReplicaReadiness(replica, 503, 30_000);
|
||||
const readiness = await probeReplica(replica, '/health/ready');
|
||||
expectBoundedError(
|
||||
readiness.status,
|
||||
readiness.text,
|
||||
readiness.requestId,
|
||||
);
|
||||
|
||||
expectBoundedOutage(await request<ApiErrorBody>('/health/ready'));
|
||||
// Redis still answers, so these requests reach the database layer and
|
||||
// must fail with the bounded 503, not an unhandled 500.
|
||||
const me = await probeReplica(replica, '/api/v1/users/me', {
|
||||
headers: bearer(token),
|
||||
});
|
||||
expectBoundedError(me.status, me.text, me.requestId);
|
||||
|
||||
// Redis still answers, so these requests reach the database layer.
|
||||
expectBoundedOutage(
|
||||
const chats = await probeReplica(replica, '/api/v1/chats', {
|
||||
headers: bearer(token),
|
||||
});
|
||||
expectBoundedError(chats.status, chats.text, chats.requestId);
|
||||
|
||||
const history = await probeReplica(
|
||||
replica,
|
||||
`/api/v1/chats/${chat.id}/messages?limit=100`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
expectBoundedError(history.status, history.text, history.requestId);
|
||||
|
||||
const registration = await probeReplica(replica, '/api/v1/users', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: `outage_${runId}_late`,
|
||||
display_name: 'Отказ зависимости',
|
||||
password,
|
||||
}),
|
||||
});
|
||||
expectBoundedError(
|
||||
registration.status,
|
||||
registration.text,
|
||||
registration.requestId,
|
||||
);
|
||||
|
||||
// Every replica loses the shared database; a client keeps getting 503,
|
||||
// first from a replica and then from the LB itself.
|
||||
expectUnavailableThroughLb(
|
||||
await request<ApiErrorBody>('/api/v1/users/me', {
|
||||
headers: bearer(token),
|
||||
}),
|
||||
);
|
||||
|
||||
expectBoundedOutage(
|
||||
await request<ApiErrorBody>('/api/v1/chats', {
|
||||
headers: bearer(token),
|
||||
}),
|
||||
await waitForSlot(
|
||||
(slots) => upSlots(slots).length === 0,
|
||||
'not every slot left rotation',
|
||||
);
|
||||
|
||||
expectBoundedOutage(
|
||||
await request<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.id}/messages?limit=100`,
|
||||
{ headers: bearer(token) },
|
||||
),
|
||||
);
|
||||
|
||||
expectBoundedOutage(
|
||||
await request<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: `outage_${runId}_late`,
|
||||
display_name: 'Отказ зависимости',
|
||||
password,
|
||||
}),
|
||||
),
|
||||
expectLbOutage(
|
||||
await request('/api/v1/users/me', { headers: bearer(token) }),
|
||||
);
|
||||
|
||||
await compose('start', postgresService);
|
||||
await waitForReadiness(200);
|
||||
await waitForSlot(
|
||||
(slots) => upSlots(slots).length === replicas.length,
|
||||
'backends did not return to rotation',
|
||||
30_000,
|
||||
);
|
||||
|
||||
const recovered = await request<User>('/api/v1/users/me', {
|
||||
headers: bearer(token),
|
||||
@@ -282,9 +704,9 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
expect(recovered.response.status).toBe(200);
|
||||
expect(recovered.body.id).toBe(user.id);
|
||||
|
||||
const history = await historyOf(chat.id, token);
|
||||
expect(history.response.status).toBe(200);
|
||||
expect(history.body.items.map((item) => item.id)).toContain(
|
||||
const after = await historyOf(chat.id, token);
|
||||
expect(after.response.status).toBe(200);
|
||||
expect(after.body.items.map((item) => item.id)).toContain(
|
||||
message.id,
|
||||
);
|
||||
|
||||
@@ -296,4 +718,96 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
},
|
||||
outagedRequestBudgetMs,
|
||||
);
|
||||
|
||||
it(
|
||||
'excludes only the replica that lost its own database path',
|
||||
async () => {
|
||||
const selected = replicas[0];
|
||||
const healthy = replicas[1];
|
||||
const selectedIp = await containerIp(selected);
|
||||
const selectedAddress = `${selectedIp}:8080`;
|
||||
const selectedInstance = (
|
||||
await probeReplica(selected, '/health/live')
|
||||
).instanceId;
|
||||
expect(selectedInstance).not.toBeNull();
|
||||
const healthyInstance = (
|
||||
await probeReplica(healthy, '/health/live')
|
||||
).instanceId;
|
||||
|
||||
try {
|
||||
await applyReplicaDatabaseReject(selectedIp);
|
||||
const faultAt = Date.now();
|
||||
|
||||
// The selected replica reports the loss, the healthy one does not.
|
||||
await waitForReplicaReadiness(selected, 503, 30_000);
|
||||
expect(
|
||||
(await probeReplica(healthy, '/health/ready')).status,
|
||||
).toBe(200);
|
||||
|
||||
// Only the affected slot leaves rotation. While `fall 2` counts the
|
||||
// failed checks the slot passes through "UP 1/2 (L7STS)", so the
|
||||
// wait is for DOWN itself, not for "no longer plain UP".
|
||||
const slots = await waitForSlot(
|
||||
(candidates) =>
|
||||
upSlots(candidates).length === replicas.length - 1 &&
|
||||
candidates.some(
|
||||
(slot) =>
|
||||
slot.addr === selectedAddress &&
|
||||
slot.status === 'DOWN',
|
||||
),
|
||||
`selected slot ${selectedAddress} did not go down`,
|
||||
30_000,
|
||||
);
|
||||
// inter 500 ms × fall 2 + timeout check 500 ms + polling step 250 ms.
|
||||
expect(Date.now() - faultAt).toBeLessThan(3_000);
|
||||
expect(
|
||||
slots.find((slot) => slot.addr === selectedAddress)?.status,
|
||||
).toBe('DOWN');
|
||||
|
||||
// Traffic through the LB stays on the healthy replica: no errors
|
||||
// and no request served by the replica that lost its database.
|
||||
const served = new Set<string>();
|
||||
for (let index = 0; index < readyReads; index += 1) {
|
||||
const read = await historyOf(chat.id, token);
|
||||
expect(read.response.status).toBe(200);
|
||||
served.add(
|
||||
read.response.headers.get('x-instance-id') ?? 'unknown',
|
||||
);
|
||||
}
|
||||
expect(served.has(selectedInstance as string)).toBe(false);
|
||||
expect(served.has(healthyInstance as string)).toBe(true);
|
||||
} finally {
|
||||
await restoreDatabaseAccess();
|
||||
}
|
||||
|
||||
// The restored replica answers again and returns to rotation.
|
||||
await waitForReplicaReadiness(selected, 200, 30_000);
|
||||
await waitForSlot(
|
||||
(slots) =>
|
||||
upSlots(slots).length === replicas.length &&
|
||||
slots.some(
|
||||
(slot) =>
|
||||
slot.addr === selectedAddress &&
|
||||
slot.status === 'UP',
|
||||
),
|
||||
'restored replica did not return to rotation',
|
||||
30_000,
|
||||
);
|
||||
|
||||
let servedAgain = false;
|
||||
for (
|
||||
let index = 0;
|
||||
index < readyReads * 2 && !servedAgain;
|
||||
index += 1
|
||||
) {
|
||||
const read = await historyOf(chat.id, token);
|
||||
expect(read.response.status).toBe(200);
|
||||
servedAgain =
|
||||
read.response.headers.get('x-instance-id') ===
|
||||
selectedInstance;
|
||||
}
|
||||
expect(servedAgain).toBe(true);
|
||||
},
|
||||
outagedRequestBudgetMs,
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user