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:
@@ -0,0 +1,231 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type pg from 'pg';
|
||||
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
|
||||
import type { Page } from '../common/http/page.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import { ChatsService } from '../chats/chats.service.js';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import type { CreateMessageDto } from './dto/create-message.dto.js';
|
||||
import type { Message } from './message.js';
|
||||
import { MessagesRepository } from './messages.repository.js';
|
||||
import { MessagesCacheService } from './cache/messages-cache.service.js';
|
||||
import {
|
||||
IDEMPOTENCY_KEY_PATTERN,
|
||||
idempotencyFingerprint,
|
||||
messagesPath,
|
||||
} from './idempotency/idempotency.js';
|
||||
import { IdempotencyRepository } from './idempotency/idempotency.repository.js';
|
||||
|
||||
// A claim row can disappear between our failed insert attempt and the read
|
||||
// (the previous owner rolled back), so a bounded retry is part of the protocol.
|
||||
const MAX_CLAIM_ATTEMPTS = 3;
|
||||
const PURGE_EVERY_REQUESTS = 512;
|
||||
|
||||
type CreateOutcome =
|
||||
| { kind: 'created'; message: Message }
|
||||
| { kind: 'replayed'; message: Message }
|
||||
| { kind: 'retry' };
|
||||
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
private readonly logger = new Logger(MessagesService.name);
|
||||
private requestsSincePurge = 0;
|
||||
|
||||
constructor(
|
||||
private readonly messagesRepository: MessagesRepository,
|
||||
private readonly chatsService: ChatsService,
|
||||
private readonly cache: MessagesCacheService,
|
||||
private readonly idempotency: IdempotencyRepository,
|
||||
private readonly database: DatabaseClient,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
chatId: string,
|
||||
input: CreateMessageDto,
|
||||
currentUser: User,
|
||||
rawKey: string | string[] | undefined,
|
||||
): Promise<Message> {
|
||||
// The key is validated before anything else: a missing, malformed or
|
||||
// duplicated header is a client error, never a stored result.
|
||||
if (typeof rawKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(rawKey))
|
||||
throw new BadRequestException(
|
||||
'Idempotency-Key header is required',
|
||||
);
|
||||
if ([...input.text].every((character) => /\s/u.test(character)))
|
||||
throw new BadRequestException('Message text cannot be blank');
|
||||
await this.chatsService.getForUser(chatId, currentUser);
|
||||
|
||||
const path = messagesPath(chatId);
|
||||
const fingerprint = idempotencyFingerprint(input);
|
||||
for (let attempt = 1; attempt <= MAX_CLAIM_ATTEMPTS; attempt += 1) {
|
||||
const outcome = await this.database.withTransaction((client) =>
|
||||
this.attemptCreate(client, {
|
||||
chatId,
|
||||
path,
|
||||
key: rawKey,
|
||||
fingerprint,
|
||||
text: input.text,
|
||||
userId: currentUser.id,
|
||||
}),
|
||||
);
|
||||
if (outcome.kind !== 'retry') {
|
||||
this.scheduleExpiredPurge();
|
||||
return outcome.message;
|
||||
}
|
||||
}
|
||||
throw new ServiceUnavailableException(
|
||||
'Idempotency key could not be claimed',
|
||||
);
|
||||
}
|
||||
|
||||
// One attempt = one transaction: the claim, the side effect and the stored
|
||||
// response commit together, so a retry can never duplicate a message and a
|
||||
// failure never leaves a half-finished claim behind.
|
||||
private async attemptCreate(
|
||||
client: pg.PoolClient,
|
||||
request: {
|
||||
chatId: string;
|
||||
path: string;
|
||||
key: string;
|
||||
fingerprint: string;
|
||||
text: string;
|
||||
userId: string;
|
||||
},
|
||||
): Promise<CreateOutcome> {
|
||||
const { chatId, path, key, fingerprint, text, userId } = request;
|
||||
const claimed = await this.idempotency.claim(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
fingerprint,
|
||||
);
|
||||
if (claimed) {
|
||||
this.metrics.increment('idempotency.claim');
|
||||
const message = await this.messagesRepository.create(
|
||||
client,
|
||||
chatId,
|
||||
userId,
|
||||
text,
|
||||
);
|
||||
await this.idempotency.store(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
HttpStatus.CREATED,
|
||||
message,
|
||||
);
|
||||
this.metrics.increment('messages.write');
|
||||
return { kind: 'created', message };
|
||||
}
|
||||
|
||||
const record = await this.idempotency.read(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS'),
|
||||
);
|
||||
if (!record) {
|
||||
// The previous owner aborted, so nothing was created and the key is
|
||||
// free again.
|
||||
this.metrics.increment('idempotency.claim_lost');
|
||||
return { kind: 'retry' };
|
||||
}
|
||||
if (record.request_fingerprint !== fingerprint) {
|
||||
this.metrics.increment('idempotency.conflict');
|
||||
throw new ConflictException(
|
||||
'Idempotency key reused with a different body',
|
||||
);
|
||||
}
|
||||
if (record.expired) {
|
||||
this.metrics.increment('idempotency.released');
|
||||
await this.idempotency.forget(client, userId, path, key);
|
||||
return { kind: 'retry' };
|
||||
}
|
||||
// A replay re-checks access, as the contract requires: the stored result
|
||||
// is only returned to a caller that may still read this chat.
|
||||
if (!(await this.idempotency.isMember(client, chatId, userId)))
|
||||
throw new NotFoundException();
|
||||
this.metrics.increment('idempotency.replay');
|
||||
return { kind: 'replayed', message: record.response_body };
|
||||
}
|
||||
|
||||
// Expired claims are storage hygiene, not part of the request: the pass runs
|
||||
// outside the request transaction, at most once per PURGE_EVERY_REQUESTS
|
||||
// successful writes, and its failure never changes the client's result.
|
||||
private scheduleExpiredPurge(): void {
|
||||
this.requestsSincePurge += 1;
|
||||
if (this.requestsSincePurge < PURGE_EVERY_REQUESTS) return;
|
||||
this.requestsSincePurge = 0;
|
||||
const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS');
|
||||
void this.idempotency
|
||||
.purgeExpired(ttl)
|
||||
.then((purged) => {
|
||||
if (purged > 0) this.metrics.increment('idempotency.purged');
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
this.metrics.increment('idempotency.purge_error');
|
||||
this.logger.warn(
|
||||
`Idempotency purge failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async list(
|
||||
chatId: string,
|
||||
currentUser: User,
|
||||
limit: number,
|
||||
cursorValue?: string,
|
||||
): Promise<Page<Message>> {
|
||||
await this.chatsService.getForUser(chatId, currentUser);
|
||||
const scope = `messages:${chatId}`;
|
||||
const cursor = cursorValue
|
||||
? decodeCursor(cursorValue, scope)
|
||||
: undefined;
|
||||
const version = await this.messagesRepository.getVersion(
|
||||
chatId,
|
||||
currentUser.id,
|
||||
);
|
||||
const page = await this.cache.getOrLoad(
|
||||
chatId,
|
||||
version,
|
||||
cursorValue,
|
||||
limit,
|
||||
async () => {
|
||||
const loaded = await this.messagesRepository.findPage(
|
||||
chatId,
|
||||
limit,
|
||||
cursor,
|
||||
);
|
||||
const lastLoaded = loaded.items.at(-1);
|
||||
return {
|
||||
items: loaded.items,
|
||||
next_cursor:
|
||||
loaded.hasMore && lastLoaded
|
||||
? encodeCursor({
|
||||
scope,
|
||||
created_at: lastLoaded.created_at,
|
||||
id: lastLoaded.id,
|
||||
})
|
||||
: null,
|
||||
};
|
||||
},
|
||||
);
|
||||
return page as Page<Message>;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user