lab3: проба готовности на отдельном соединении, серия роста на блоке why#
This commit is contained in:
@@ -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> {
|
||||
|
||||
Reference in New Issue
Block a user