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
+85
View File
@@ -0,0 +1,85 @@
import { BadRequestException } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import { decodeCursor, encodeCursor } from './cursor.js';
const scope = 'messages:6f1c2a3e-1111-4222-8333-444455556666';
function encode(createdAt: string, cursorScope = scope): string {
return encodeCursor({
scope: cursorScope,
created_at: createdAt,
id: randomUUID(),
});
}
describe('decodeCursor', () => {
it('accepts valid instants and normalizes them to canonical milliseconds', () => {
const accepted: Array<[string, string]> = [
['2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'],
['2026-01-01T00:00:00Z', '2026-01-01T00:00:00.000Z'],
['2026-01-01T00:00:00.999999Z', '2026-01-01T00:00:00.999Z'],
['2024-02-29T23:59:59.000Z', '2024-02-29T23:59:59.000Z'],
['2026-12-31T23:59:59.999Z', '2026-12-31T23:59:59.999Z'],
];
for (const [createdAt, expected] of accepted) {
const decoded = decodeCursor(encode(createdAt), scope);
expect(decoded.created_at).toBe(expected);
expect(decoded.scope).toBe(scope);
}
});
it('rejects calendar dates that the platform parser rolls over', () => {
// 2026-02-31 would silently become 2026-03-03 and then fail inside SQL.
for (const createdAt of [
'2026-02-31T00:00:00.000Z',
'2025-02-29T00:00:00.000Z',
'2026-04-31T00:00:00.000Z',
'2026-06-31T12:00:00.000Z',
]) {
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
BadRequestException,
);
}
});
it('rejects out-of-range and malformed timestamps', () => {
for (const createdAt of [
'2026-01-01T24:00:00.000Z',
'2026-01-01T00:00:60.000Z',
'2026-13-01T00:00:00.000Z',
'2026-00-01T00:00:00.000Z',
'2026-01-01T00:00:00',
'2026-01-01T00:00:00+02:00',
'2026-1-1T00:00:00.000Z',
'2026-01-01',
'not-a-timestamp',
]) {
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
BadRequestException,
);
}
});
it('rejects a cursor from another scope, a malformed id, and non-cursor input', () => {
expect(() =>
decodeCursor(
encode('2026-01-01T00:00:00.000Z', 'messages:other'),
scope,
),
).toThrow(BadRequestException);
expect(() =>
decodeCursor(
encodeCursor({
scope,
created_at: '2026-01-01T00:00:00.000Z',
id: 'not-a-uuid',
}),
scope,
),
).toThrow(BadRequestException);
expect(() => decodeCursor('not-a-cursor', scope)).toThrow(
BadRequestException,
);
});
});
+54
View File
@@ -0,0 +1,54 @@
import { BadRequestException } from '@nestjs/common';
import { isValid, parseISO } from 'date-fns';
export type Cursor = {
scope: string;
created_at: string;
id: string;
};
// Format check for the canonical API shape: `Date.prototype.toISOString()` with
// optional fractional seconds. Explicit ranges reject values such as 24:00:00.
// Calendar validity (2026-02-31, 2025-02-29, 2026-04-31) is checked by
// date-fns `parseISO`, which refuses impossible dates that the platform parser
// would silently roll over into another day.
const CURSOR_TIMESTAMP =
/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?Z$/u;
export function encodeCursor(cursor: Cursor): string {
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
}
export function decodeCursor(value: string, expectedScope: string): Cursor {
try {
const parsed: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
typeof parsed !== 'object' ||
parsed === null ||
!('scope' in parsed) ||
!('created_at' in parsed) ||
!('id' in parsed) ||
typeof parsed.scope !== 'string' ||
typeof parsed.created_at !== 'string' ||
typeof parsed.id !== 'string' ||
parsed.scope !== expectedScope ||
!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(
parsed.id,
) ||
!CURSOR_TIMESTAMP.test(parsed.created_at)
)
throw new Error('invalid cursor');
const instant = parseISO(parsed.created_at);
if (!isValid(instant)) throw new Error('invalid cursor');
return {
scope: parsed.scope,
created_at: instant.toISOString(),
id: parsed.id,
};
} catch {
throw new BadRequestException('Invalid cursor');
}
}
+4
View File
@@ -0,0 +1,4 @@
export type Page<T> = {
items: T[];
next_cursor: string | null;
};
@@ -0,0 +1,59 @@
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),
),
);
}
}