lab3: идентичность реплики, LB-проверка и общая идемпотентность отправки

Этот коммит впервые фиксирует порт lab2 (приложение NestJS+Fastify, Dockerfile,
одноservice-стенд compose, restart hook) и добавляет уровень 3/4 по lab3:

- X-Instance-Id = INSTANCE_ID либо hostname контейнера (стабилен для процесса),
  добавляется и в ответах об ошибках, которые формируются до интерсептора.
- /internal/lb-check: проба LB, намеренно не зависящая от PostgreSQL и Redis
  (отказ общей БД нельзя лечить выводом реплик из ротации); /health/ready
  остаётся операторским сигналом. /internal/metrics отдаёт instance_id и build_id.
- Общая идемпотентность POST сообщения: таблица idempotency_keys, область
  (user, method, path, key), канонический отпечаток тела, заявка+результат в
  одной транзакции, повтор возвращает сохранённый ответ, другое тело — 409,
  отсутствие/неверный ключ — 400, просрочка по IDEMPOTENCY_TTL_SECONDS.
- Транзиентные коды PostgreSQL (57014/40001/40P01) отображаются в 503, чтобы
  прерывание не фиксировалось идемпотентной записью как окончательный результат.
- Миграции 003 (идемпотентность) и 004 (pg_stat_statements для трека 1),
  операторский прогон GC: npm run idempotency:gc.
This commit is contained in:
2026-10-15 21:09:23 +03:00
parent 0ab3a341aa
commit e9cd28d6ba
83 changed files with 12099 additions and 2 deletions
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from 'vitest';
import { ServiceUnavailableException } from '@nestjs/common';
import { HealthService } from './health.service.js';
describe('HealthService', () => {
it('reports liveness and readiness when dependencies are healthy', async () => {
const database = { health: vi.fn().mockResolvedValue(undefined) };
const redis = { health: vi.fn().mockResolvedValue(undefined) };
const config = { get: vi.fn().mockReturnValue(0) };
const service = new HealthService(
database as never,
redis as never,
config as never,
);
expect(service.getLiveness()).toEqual({ status: 'ok' });
await expect(service.getReadiness()).resolves.toEqual({ status: 'ok' });
});
it('rejects readiness when a dependency is unavailable', async () => {
const database = {
health: vi.fn().mockRejectedValue(new Error('down')),
};
const redis = { health: vi.fn().mockResolvedValue(undefined) };
const service = new HealthService(
database as never,
redis as never,
{ get: vi.fn() } as never,
);
await expect(service.getReadiness()).rejects.toBeInstanceOf(
ServiceUnavailableException,
);
});
it('keeps liveness healthy while draining', async () => {
const service = new HealthService(
{ health: vi.fn() } as never,
{ health: vi.fn() } as never,
{ get: vi.fn() } as never,
);
service.setDraining();
expect(service.getLiveness()).toEqual({ status: 'ok' });
await expect(service.getReadiness()).rejects.toThrow(
'Service is shutting down',
);
});
it('keeps the load-balancer check positive while a dependency is down', async () => {
const service = new HealthService(
{ health: vi.fn().mockRejectedValue(new Error('down')) } as never,
{ health: vi.fn().mockRejectedValue(new Error('down')) } as never,
{ get: vi.fn() } as never,
);
expect(service.getLbCheck()).toEqual({ status: 'ok' });
service.setDraining();
expect(() => service.getLbCheck()).toThrow('Draining');
});
});