- compose.yaml: проект mtusi-lab3, HAProxy как единственная точка входа,
deploy.replicas ${API_REPLICAS:-2}, CPU/RAM-лимиты на каждый сервис,
stop_grace_period 20s, лимиты из переменных (API_CPUS_PER_REPLICA и т.д.),
loopback-порты PostgreSQL/Redis только для операторских проверок; у API
портов нет; container_name нигде не задан.
- infra/haproxy/haproxy.cfg: проба GET /internal/lb-check, inter 500ms/fall 2
(~1s обнаружение), server-template + DNS Docker вместо статического списка,
stats на 127.0.0.1:8404.
- Дрейн: SIGTERM -> реплика сразу перестаёт проходить пробу LB -> пауза
DRAIN_DELAY_MS -> закрытие сервера и пулов. Nest уничтожает провайдеров
раньше beforeApplicationShutdown, поэтому последовательность вынесена в
main.ts, а HealthService отвечает только за флаг not-ready.
- scripts/stop-one.sh (остановка ровно одной реплики по X-Instance-Id),
scripts/start-replica.sh (восстановление до API_REPLICAS), scripts/quiesce.sh
(остановка/возврат посторонних контейнеров хоста), restart.sh перезапускает
и LB, scripts/app-e2e.sh (host-side e2e через loopback-порты).
- Makefile: stand-up/down/status, stand-replica, wait-ready, quiesce-up/down,
test-e2e, test-failover-all, rolling-update, track1, evidence.
- Dockerfile: ARG/ENV BUILD_ID для доказательства rolling update.
Проверено: make test, make test-e2e, make test-persistence (restart.sh),
make test-failover (stop-one.sh, восстановление через start-replica.sh),
make test-dependencies; docker inspect подтверждает NanoCpus/Memory и
отсутствие опубликованных портов у api.
52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
import {
|
|
Global,
|
|
Injectable,
|
|
Module,
|
|
ServiceUnavailableException,
|
|
} from '@nestjs/common';
|
|
import { DatabaseClient } from '../database/database.client.js';
|
|
import { RedisClient } from '../redis/redis.client.js';
|
|
|
|
@Injectable()
|
|
export class HealthService {
|
|
private ready = true;
|
|
constructor(
|
|
private readonly database: DatabaseClient,
|
|
private readonly redis: RedisClient,
|
|
) {}
|
|
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');
|
|
try {
|
|
await Promise.all([this.database.health(), this.redis.health()]);
|
|
} catch {
|
|
throw new ServiceUnavailableException('Dependencies unavailable');
|
|
}
|
|
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.
|
|
setDraining() {
|
|
this.ready = false;
|
|
}
|
|
}
|
|
|
|
@Global()
|
|
@Module({ providers: [HealthService], exports: [HealthService] })
|
|
export class HealthServiceModule {}
|