forked from mtusi2026/mtusi2026lab6
Перенесено дерево 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.
97 lines
3.2 KiB
TypeScript
97 lines
3.2 KiB
TypeScript
import { NestFactory } from '@nestjs/core';
|
|
import { HttpAdapterHost } from '@nestjs/core';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { ValidationPipe } from '@nestjs/common';
|
|
import type { UploadRequest } from './attachments/upload-request.js';
|
|
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';
|
|
|
|
const UPLOAD_ROUTE = '/api/v1/chats/:chatId/attachments';
|
|
const UPLOAD_STREAM_TYPE = 'application/x-messenger-upload-stream';
|
|
|
|
async function bootstrap(): Promise<void> {
|
|
const app = await NestFactory.create<NestFastifyApplication>(
|
|
AppModule,
|
|
new FastifyAdapter({ logger: true }),
|
|
);
|
|
// The upload route receives its body as an unread stream whatever the
|
|
// declared Content-Type: the service checks the type itself, after the
|
|
// auth guard (401 before 415, contracts/README.md), and bounds the body by
|
|
// its own limits, not Fastify's bodyLimit. The declared type is kept on the
|
|
// request; all other routes keep Fastify's parsers untouched.
|
|
const fastify = app.getHttpAdapter().getInstance();
|
|
fastify.addHook(
|
|
'onRequest',
|
|
(request: UploadRequest, _reply: unknown, done: () => void) => {
|
|
if (
|
|
request.method === 'POST' &&
|
|
request.routeOptions?.url === UPLOAD_ROUTE
|
|
) {
|
|
request.uploadContentType = request.headers['content-type'];
|
|
request.headers['content-type'] = UPLOAD_STREAM_TYPE;
|
|
}
|
|
done();
|
|
},
|
|
);
|
|
fastify.addContentTypeParser(
|
|
UPLOAD_STREAM_TYPE,
|
|
(
|
|
_request: unknown,
|
|
payload: unknown,
|
|
done: (error: Error | null, body?: unknown) => void,
|
|
) => done(null, payload),
|
|
);
|
|
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();
|