lab6: базовый коммит из lab5 (0790599)

Перенесено дерево lab5 целиком: NestJS-приложение (API + worker,
RabbitMQ, outbox, S3), Dockerfile, compose.yaml, infra/{haproxy,minio,
rabbitmq}, стендовые скрипты, scripts/lab4, scripts/lab5,
evidence/lab4, evidence/lab5 и contracts/extensions.openapi.json.

Задание lab6 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,
examples,observability}, tests, compose.example.yaml, infra/otel,
.github/pull_request_template.md.

Адаптации при переносе:
- docker-проект mtusi-lab5 -> mtusi-lab6 и тег образа
  mtusi-messenger:lab6 (compose.yaml, scripts/stop-one.sh, .env.example,
  infra/README.md), чтобы тома и контейнеры не пересекались с lab5;
- Makefile: цели lab5 сохранены целиком (skeleton lab6 не отличается
  от skeleton lab5);
- .env.example: переменные приложения и стенда lab5 + блок lab6
  (OTEL_*) из skeleton.
This commit is contained in:
2026-11-09 16:44:21 +03:00
parent 470d9d6f1e
commit 6889e77ab4
203 changed files with 27707 additions and 13 deletions
+17
View File
@@ -0,0 +1,17 @@
import { Controller, Get } from '@nestjs/common';
import { HealthService } from './health.service.js';
@Controller('health')
export class HealthController {
constructor(private readonly healthService: HealthService) {}
@Get('live')
getLive() {
return this.healthService.getLiveness();
}
@Get('ready')
async getReady() {
return this.healthService.getReadiness();
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { HealthController } from './health.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],
providers: [HealthService],
})
export class HealthModule {}
+91
View File
@@ -0,0 +1,91 @@
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 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' });
});
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,
{ 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,
);
});
it('keeps liveness healthy while draining', async () => {
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' });
await expect(service.getReadiness()).rejects.toThrow(
'Service is shutting down',
);
});
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(
database as never,
redis as never,
{ getOrThrow: () => 50 } as never,
);
service.setDraining();
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,
);
});
});
+60
View File
@@ -0,0 +1,60 @@
import {
Global,
Injectable,
Module,
ServiceUnavailableException,
} 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 {
private ready = true;
constructor(
private readonly database: DatabaseClient,
private readonly redis: RedisClient,
private readonly config: ConfigService<AppConfig>,
) {}
getLiveness() {
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.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 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;
}
}
@Global()
@Module({ providers: [HealthService], exports: [HealthService] })
export class HealthServiceModule {}