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
@@ -1,17 +1,18 @@
import { Injectable } from '@nestjs/common';
import type pg from 'pg';
import pg from 'pg';
import { DatabaseClient } from '../../database/database.client.js';
import type { Message } from '../message.js';
// A committed row always carries the response: the claim and the stored response
// are written in the same transaction, so there is no poisoned intermediate
// state to re-check at replay time.
// are written by one statement, so there is no poisoned intermediate state to
// re-check at replay time.
export type IdempotencyRecord = {
request_fingerprint: string;
status_code: number;
response_body: Message;
created_at: Date | string;
expired: boolean;
is_member: boolean;
};
const PURGE_BATCH_LIMIT = 1000;
@@ -21,88 +22,48 @@ const PURGE_BATCHES = 10;
export class IdempotencyRepository {
constructor(private readonly database: DatabaseClient) {}
/** True when this request created the claim, i.e. it owns the side effect. */
async claim(
client: pg.PoolClient,
userId: string,
path: string,
key: string,
fingerprint: string,
): Promise<boolean> {
const result = await client.query({
text: `INSERT INTO idempotency_keys (user_id, method, path, key, request_fingerprint)
VALUES ($1, 'POST', $2, $3, $4)
ON CONFLICT DO NOTHING
RETURNING created_at`,
values: [userId, path, key, fingerprint],
});
return result.rowCount === 1;
}
/**
* Reads the stored result and re-checks access in the same round trip: a
* replay must still prove that the caller may read this chat.
*/
async read(
client: pg.PoolClient,
userId: string,
path: string,
key: string,
chatId: string,
ttlSeconds: number,
): Promise<IdempotencyRecord | undefined> {
const result = await client.query<IdempotencyRecord>({
text: `SELECT request_fingerprint, status_code, response_body, created_at,
created_at < now() - make_interval(secs => $4::double precision) AS expired
FROM idempotency_keys
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
values: [userId, path, key, ttlSeconds],
});
const result = await this.database.query<IdempotencyRecord>(
'idempotency.read',
`SELECT k.request_fingerprint, k.status_code, k.response_body, k.created_at,
k.created_at < now() - make_interval(secs => $4::double precision) AS expired,
EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $5 AND user_id = $1
) AS is_member
FROM idempotency_keys k
WHERE k.user_id = $1 AND k.method = 'POST' AND k.path = $2 AND k.key = $3`,
[userId, path, key, ttlSeconds, chatId],
);
return result.rows[0];
}
async store(
client: pg.PoolClient,
userId: string,
path: string,
key: string,
statusCode: number,
message: Message,
): Promise<void> {
await client.query({
text: `UPDATE idempotency_keys
SET status_code = $4, response_body = $5::jsonb, message_id = $6
async forget(userId: string, path: string, key: string): Promise<void> {
await this.database.query(
'idempotency.forget',
`DELETE FROM idempotency_keys
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
values: [
userId,
path,
key,
statusCode,
JSON.stringify(message),
message.id,
],
});
[userId, path, key],
);
}
async forget(
client: pg.PoolClient,
userId: string,
path: string,
key: string,
): Promise<void> {
await client.query({
text: `DELETE FROM idempotency_keys
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
values: [userId, path, key],
});
}
async isMember(
client: pg.PoolClient,
chatId: string,
userId: string,
): Promise<boolean> {
const result = await client.query<{ is_member: boolean }>({
text: `SELECT EXISTS (
async isMember(chatId: string, userId: string): Promise<boolean> {
const result = await this.database.query<{ is_member: boolean }>(
'messages.checkMembership',
`SELECT EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2
) AS is_member`,
values: [chatId, userId],
});
[chatId, userId],
);
return result.rows[0]?.is_member === true;
}
@@ -113,7 +74,7 @@ export class IdempotencyRepository {
* of deleted rows (0 when another replica is purging).
*/
async purgeExpired(ttlSeconds: number): Promise<number> {
const client = await this.database.pool.connect();
const client: pg.PoolClient = await this.database.pool.connect();
try {
await client.query('BEGIN');
try {
@@ -126,15 +87,15 @@ export class IdempotencyRepository {
}
let purged = 0;
for (let batch = 0; batch < PURGE_BATCHES; batch += 1) {
const result = await client.query({
text: `DELETE FROM idempotency_keys
const result = await client.query(
`DELETE FROM idempotency_keys
WHERE ctid IN (
SELECT ctid FROM idempotency_keys
WHERE created_at < now() - make_interval(secs => $1::double precision)
LIMIT ${PURGE_BATCH_LIMIT}
)`,
values: [ttlSeconds],
});
[ttlSeconds],
);
const deleted = result.rowCount ?? 0;
purged += deleted;
if (deleted < PURGE_BATCH_LIMIT) break;
+65 -27
View File
@@ -3,7 +3,6 @@ import {
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import type pg from 'pg';
import { DatabaseClient } from '../database/database.client.js';
import type { Cursor } from '../common/http/cursor.js';
import type { Message } from './message.js';
@@ -16,6 +15,15 @@ type MessageRow = {
created_at: Date | string;
};
export type CreateOnceRequest = {
userId: string;
chatId: string;
path: string;
key: string;
fingerprint: string;
text: string;
};
function toMessage(row: MessageRow): Message {
return {
id: row.id,
@@ -26,36 +34,66 @@ function toMessage(row: MessageRow): Message {
};
}
// Один оператор делает всё, что нужно пути записи: проверяет членство, занимает
// ключ идемпотентности, вставляет сообщение, увеличивает версию чата (якорь
// инвалидации кэша истории) и сохраняет тело ответа. Атомарность даёт сам
// оператор, поэтому явная транзакция и отдельные round trip'ы не нужны; тело
// ответа строится в SQL и служит единственным источником истины и для первого
// ответа, и для повторов.
//
// Зависимости CTE задают порядок выполнения: claim -> inserted -> bumped.
const CREATE_ONCE_SQL = `
WITH claim AS (
INSERT INTO idempotency_keys (user_id, method, path, key, request_fingerprint,
status_code, response_body, message_id)
SELECT $1, 'POST', $2, $3, $4, 201,
jsonb_build_object(
'id', $5::uuid,
'chat_id', $7::uuid,
'sender_id', $1::uuid,
'text', $6::text,
'created_at', to_char(date_trunc('milliseconds', now()) AT TIME ZONE 'UTC',
'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')),
$5::uuid
WHERE EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $7::uuid AND user_id = $1
)
ON CONFLICT DO NOTHING
RETURNING response_body
), inserted AS (
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT $5::uuid, $7::uuid, $1::uuid, $6::text, date_trunc('milliseconds', now())
FROM claim
RETURNING id
), bumped AS (
UPDATE chats SET message_version = message_version + 1
WHERE id = $7::uuid AND EXISTS (SELECT 1 FROM inserted)
)
SELECT response_body FROM claim`;
@Injectable()
export class MessagesRepository {
constructor(private readonly database: DatabaseClient) {}
// The caller owns the transaction: the message insert, the chat version bump
// and the idempotency claim must commit or roll back as one unit.
async create(
client: pg.PoolClient,
chatId: string,
senderId: string,
text: string,
): Promise<Message> {
const id = randomUUID();
const membership = await client.query({
name: 'messages.checkMembership',
text: 'SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2',
values: [chatId, senderId],
});
if (!membership.rowCount) throw new NotFoundException();
const result = await client.query<MessageRow>({
name: 'messages.insert',
text: 'INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at',
values: [id, chatId, senderId, text],
});
await client.query({
name: 'messages.incrementVersion',
text: 'UPDATE chats SET message_version = message_version + 1 WHERE id = $1',
values: [chatId],
});
return toMessage(result.rows[0]);
/**
* Returns the created message, or undefined when the key is already taken or
* the caller is not a member of the chat (both leave no side effect).
*/
async createOnce(request: CreateOnceRequest): Promise<Message | undefined> {
const result = await this.database.query<{ response_body: Message }>(
'messages.createIdempotent',
CREATE_ONCE_SQL,
[
request.userId,
request.path,
request.key,
request.fingerprint,
randomUUID(),
request.text,
request.chatId,
],
);
return result.rows[0]?.response_body;
}
async getVersion(chatId: string, userId: string): Promise<bigint> {
+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;