lab3: путь записи сообщения одним оператором (C2)

Владелец ключа идемпотентности больше не оркестрируется в приложении: проверка
членства, заявка ключа, вставка сообщения, инкремент версии чата (якорь
инвалидации кэша) и сохранение тела ответа выполняются одним оператором SQL,
атомарность которого обеспечивает сам оператор.

- messages.repository: createOnce() одним запросом вместо трёх (проверка
  членства + INSERT + UPDATE version) и явной транзакции; тело ответа строится
  в SQL и служит источником истины и для первого ответа, и для повторов.
- idempotency.repository: read() читает сохранённый ответ вместе с повторной
  проверкой доступа, delete/purge не изменились; claim/store внутри транзакции
  больше не нужны.
- messages.service: без DatabaseClient и без предварительного chatsService.
  getForUser в пути записи; ключ обязателен, тело проверяется до обращения к БД,
  просроченный ключ освобождается и занимается заново.

Итог: 1 round trip на запись вместо 8 и 2 вместо 3 на повтор; короче удержание
блокировки строки chats, что и проверяется A/B на профиле горячего чата.

Проверено: npm run build, tsc, unit-тесты, lint, публичный smoke и black-box
набор приложения (включая конкурентный повтор с одним ключом) на стенде с
образом mtusi-messenger:lab3-after.
This commit is contained in:
2026-10-15 22:48:22 +03:00
parent 410e1ea3ad
commit 5a5a8fe5cb
7 changed files with 601 additions and 323 deletions
+56 -102
View File
@@ -1,20 +1,17 @@
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';
@@ -27,16 +24,12 @@ import {
} 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.
// Один повтор нужен только для просроченного ключа: запись удаляется, и тот же
// оператор занимает ключ заново. Больше трёх кругов означает, что ключ
// перехватывают параллельные запросы, и честнее вернуть 503, чем крутиться.
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);
@@ -47,7 +40,6 @@ export class MessagesService {
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,
) {}
@@ -58,116 +50,78 @@ export class MessagesService {
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);
const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS');
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') {
const created = await this.messagesRepository.createOnce({
userId: currentUser.id,
chatId,
path,
key: rawKey,
fingerprint,
text: input.text,
});
if (created) {
this.metrics.increment('idempotency.claim');
this.metrics.increment('messages.write');
this.scheduleExpiredPurge();
return outcome.message;
return created;
}
const stored = await this.idempotency.read(
currentUser.id,
path,
rawKey,
chatId,
ttl,
);
if (!stored) {
// Заявки нет: либо запрос не имеет доступа к чату (404), либо
// чужую заявку сняли между нашими двумя запросами (503).
if (!(await this.idempotency.isMember(chatId, currentUser.id)))
throw new NotFoundException();
this.metrics.increment('idempotency.claim_lost');
throw new ServiceUnavailableException(
'Idempotency key could not be claimed',
);
}
if (stored.request_fingerprint !== fingerprint) {
this.metrics.increment('idempotency.conflict');
throw new ConflictException(
'Idempotency key reused with a different body',
);
}
if (stored.expired) {
this.metrics.increment('idempotency.released');
await this.idempotency.forget(
currentUser.id,
path,
rawKey,
);
continue;
}
if (!stored.is_member) throw new NotFoundException();
this.metrics.increment('idempotency.replay');
return stored.response_body;
}
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.
// outside the request path, 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;