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,152 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type 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.
|
||||
export type IdempotencyRecord = {
|
||||
request_fingerprint: string;
|
||||
status_code: number;
|
||||
response_body: Message;
|
||||
created_at: Date | string;
|
||||
expired: boolean;
|
||||
};
|
||||
|
||||
const PURGE_BATCH_LIMIT = 1000;
|
||||
const PURGE_BATCHES = 10;
|
||||
|
||||
@Injectable()
|
||||
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;
|
||||
}
|
||||
|
||||
async read(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: 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],
|
||||
});
|
||||
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
|
||||
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
|
||||
values: [
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
statusCode,
|
||||
JSON.stringify(message),
|
||||
message.id,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
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 (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2
|
||||
) AS is_member`,
|
||||
values: [chatId, userId],
|
||||
});
|
||||
return result.rows[0]?.is_member === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes expired claims in bounded batches. The transaction-scoped advisory
|
||||
* lock makes the pass single-flight across replicas without risking a lock
|
||||
* leaking back into the pool with a released connection. Returns the number
|
||||
* of deleted rows (0 when another replica is purging).
|
||||
*/
|
||||
async purgeExpired(ttlSeconds: number): Promise<number> {
|
||||
const client = await this.database.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
try {
|
||||
const lock = await client.query<{ locked: boolean }>(
|
||||
"SELECT pg_try_advisory_xact_lock(hashtext('idempotency_gc')) AS locked",
|
||||
);
|
||||
if (lock.rows[0]?.locked !== true) {
|
||||
await client.query('ROLLBACK');
|
||||
return 0;
|
||||
}
|
||||
let purged = 0;
|
||||
for (let batch = 0; batch < PURGE_BATCHES; batch += 1) {
|
||||
const result = await client.query({
|
||||
text: `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],
|
||||
});
|
||||
const deleted = result.rowCount ?? 0;
|
||||
purged += deleted;
|
||||
if (deleted < PURGE_BATCH_LIMIT) break;
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
return purged;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user