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:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user