Этот коммит впервые фиксирует порт 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.
60 lines
1.7 KiB
TypeScript
60 lines
1.7 KiB
TypeScript
import {
|
|
CallHandler,
|
|
ExecutionContext,
|
|
Injectable,
|
|
NestInterceptor,
|
|
} from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { HttpAdapterHost } from '@nestjs/core';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { finalize, Observable } from 'rxjs';
|
|
import type { AppConfig } from '../../config/app-config.schema.js';
|
|
import { resolveInstanceId } from '../../config/instance-id.js';
|
|
import { MetricsService } from '../../metrics/metrics.service.js';
|
|
|
|
type RequestWithId = { requestId?: string };
|
|
|
|
@Injectable()
|
|
export class RequestIdInterceptor implements NestInterceptor {
|
|
// Resolved once: the identity must be stable for the whole process lifetime,
|
|
// otherwise a client cannot tell whether it moved to another replica.
|
|
private readonly instanceId: string;
|
|
|
|
constructor(
|
|
private readonly adapterHost: HttpAdapterHost,
|
|
private readonly metrics: MetricsService,
|
|
config: ConfigService<AppConfig>,
|
|
) {
|
|
this.instanceId = resolveInstanceId(config);
|
|
}
|
|
|
|
intercept(
|
|
context: ExecutionContext,
|
|
next: CallHandler,
|
|
): Observable<unknown> {
|
|
const request = context.switchToHttp().getRequest<RequestWithId>();
|
|
const response = context.switchToHttp().getResponse<unknown>();
|
|
const requestId = randomUUID();
|
|
const startedAt = performance.now();
|
|
request.requestId = requestId;
|
|
this.adapterHost.httpAdapter.setHeader(
|
|
response,
|
|
'X-Request-Id',
|
|
requestId,
|
|
);
|
|
this.adapterHost.httpAdapter.setHeader(
|
|
response,
|
|
'X-Instance-Id',
|
|
this.instanceId,
|
|
);
|
|
this.metrics.increment('request_count');
|
|
return next
|
|
.handle()
|
|
.pipe(
|
|
finalize(() =>
|
|
this.metrics.observeLatency(performance.now() - startedAt),
|
|
),
|
|
);
|
|
}
|
|
}
|