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
+54
View File
@@ -0,0 +1,54 @@
import {
Controller,
Get,
Headers,
HttpCode,
HttpStatus,
Post,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { AppConfig } from '../config/app-config.schema.js';
import { resolveInstanceId } from '../config/instance-id.js';
import { MetricsService } from './metrics.service.js';
@Controller('internal')
export class MetricsController {
private readonly instanceId: string;
private readonly buildId: string;
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.instanceId = resolveInstanceId(config);
this.buildId = process.env.BUILD_ID ?? 'unknown';
}
@Get('metrics')
get(@Headers('authorization') authorization?: string) {
this.requireToken(authorization);
return {
...this.metrics.snapshot(),
instance_id: this.instanceId,
build_id: this.buildId,
};
}
@Post('metrics/reset')
@HttpCode(HttpStatus.OK)
reset(@Headers('authorization') authorization?: string): { status: 'ok' } {
this.requireToken(authorization);
this.metrics.reset();
return { status: 'ok' };
}
private requireToken(authorization?: string): void {
const token = this.config.get<string>('METRICS_TOKEN');
if (!token || authorization !== `Bearer ${token}`)
throw new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="metrics"',
});
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { MetricsController } from './metrics.controller.js';
import { MetricsService } from './metrics.service.js';
@Module({
controllers: [MetricsController],
providers: [MetricsService],
exports: [MetricsService],
})
export class MetricsModule {}
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest';
import { MetricsService } from './metrics.service.js';
describe('MetricsService', () => {
it('computes nearest-rank percentiles from observed latencies', () => {
const metrics = new MetricsService();
metrics.increment('cache_hit');
metrics.increment('cache_hit');
metrics.observeLatency(30);
metrics.observeLatency(10);
metrics.observeLatency(20);
expect(metrics.snapshot()).toEqual({
counters: { cache_hit: 2 },
latency_ms: {
count: 3,
sample_count: 3,
p50: 20,
p95: 30,
p99: 30,
max: 30,
},
});
});
it('keeps snapshots isolated from callers and later observations', () => {
const metrics = new MetricsService();
metrics.increment('cache_hit');
const snapshot = metrics.snapshot();
snapshot.counters.cache_hit = 99;
metrics.increment('cache_hit');
expect(metrics.snapshot().counters.cache_hit).toBe(2);
expect(snapshot.latency_ms.count).toBe(0);
});
it('bounds retained samples but keeps cumulative count and maximum', () => {
const metrics = new MetricsService();
metrics.observeLatency(9000);
for (let index = 0; index < 4096; index += 1)
metrics.observeLatency(10);
expect(metrics.snapshot().latency_ms).toEqual({
count: 4097,
sample_count: 4096,
p50: 10,
p95: 10,
p99: 10,
max: 9000,
});
});
it('ignores invalid latency observations', () => {
const metrics = new MetricsService();
for (const value of [-1, NaN, Infinity]) metrics.observeLatency(value);
expect(metrics.snapshot().latency_ms).toEqual({
count: 0,
sample_count: 0,
p50: 0,
p95: 0,
p99: 0,
max: 0,
});
});
});
+69
View File
@@ -0,0 +1,69 @@
import { Injectable } from '@nestjs/common';
const LATENCY_SAMPLE_CAPACITY = 4096;
type LatencySnapshot = {
count: number;
sample_count: number;
p50: number;
p95: number;
p99: number;
max: number;
};
@Injectable()
export class MetricsService {
private readonly counters: Record<string, number> = {};
private readonly latencies: number[] = [];
private latencyCount = 0;
private maximumLatency = 0;
private nextSample = 0;
increment(name: string): void {
this.counters[name] = (this.counters[name] ?? 0) + 1;
}
observeLatency(milliseconds: number): void {
if (!Number.isFinite(milliseconds) || milliseconds < 0) return;
this.latencyCount += 1;
this.maximumLatency = Math.max(this.maximumLatency, milliseconds);
this.latencies[this.nextSample] = milliseconds;
this.nextSample = (this.nextSample + 1) % LATENCY_SAMPLE_CAPACITY;
}
snapshot(): {
counters: Record<string, number>;
latency_ms: LatencySnapshot;
} {
const sorted = [...this.latencies].sort((left, right) => left - right);
return {
counters: { ...this.counters },
latency_ms: {
count: this.latencyCount,
sample_count: sorted.length,
p50: this.percentile(sorted, 0.5),
p95: this.percentile(sorted, 0.95),
p99: this.percentile(sorted, 0.99),
max: this.maximumLatency,
},
};
}
reset(): void {
for (const name of Object.keys(this.counters))
delete this.counters[name];
this.latencies.length = 0;
this.latencyCount = 0;
this.maximumLatency = 0;
this.nextSample = 0;
}
private percentile(sorted: number[], percentile: number): number {
if (sorted.length === 0) return 0;
const index = Math.min(
sorted.length - 1,
Math.ceil(sorted.length * percentile) - 1,
);
return sorted[index];
}
}