Files
mtusi2026lab3/app/src/main.ts
T
ilya.tyunin 917ed1a734 lab3: стенд HAProxy + реплики под compose, лимиты, хуки остановки и квиесценции
- 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.
2026-10-15 21:14:17 +03:00

64 lines
2.0 KiB
TypeScript

import { NestFactory } from '@nestjs/core';
import { HttpAdapterHost } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe } from '@nestjs/common';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module.js';
import { HealthService } from './health/health.service.js';
import { MetricsService } from './metrics/metrics.service.js';
import { RequestIdInterceptor } from './common/http/request-id.interceptor.js';
async function bootstrap(): Promise<void> {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ logger: true }),
);
app.useGlobalInterceptors(
new RequestIdInterceptor(
app.get(HttpAdapterHost),
app.get(MetricsService),
app.get(ConfigService),
),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
const config = app.get(ConfigService);
const port = config.getOrThrow<number>('APP_PORT');
const host = config.getOrThrow<string>('APP_HOST');
await app.listen(port, host);
// Drain before teardown. Nest's own shutdown sequence destroys providers
// (closing the database pool and Redis) before `beforeApplicationShutdown`
// runs, so relying on it would keep the replica listed in the load balancer
// while it can no longer serve: SIGTERM must first turn the replica
// not-ready for the LB probe, then wait DRAIN_DELAY_MS, and only then close
// the server and the pools.
const health = app.get(HealthService);
const drainDelayMs = config.getOrThrow<number>('DRAIN_DELAY_MS');
let shuttingDown = false;
const shutdown = async (): Promise<void> => {
if (shuttingDown) return;
shuttingDown = true;
health.setDraining();
if (drainDelayMs > 0)
await new Promise<void>((resolve) => setTimeout(resolve, drainDelayMs));
await app.close();
process.exit(0);
};
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const)
process.once(signal, () => {
void shutdown();
});
}
await bootstrap();