forked from mtusi2026/mtusi2026lab6
lab6: базовый коммит из lab5 (0790599)
Перенесено дерево lab5 целиком: NestJS-приложение (API + worker,
RabbitMQ, outbox, S3), Dockerfile, compose.yaml, infra/{haproxy,minio,
rabbitmq}, стендовые скрипты, scripts/lab4, scripts/lab5,
evidence/lab4, evidence/lab5 и contracts/extensions.openapi.json.
Задание lab6 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,
examples,observability}, tests, compose.example.yaml, infra/otel,
.github/pull_request_template.md.
Адаптации при переносе:
- docker-проект mtusi-lab5 -> mtusi-lab6 и тег образа
mtusi-messenger:lab6 (compose.yaml, scripts/stop-one.sh, .env.example,
infra/README.md), чтобы тома и контейнеры не пересекались с lab5;
- Makefile: цели lab5 сохранены целиком (skeleton lab6 не отличается
от skeleton lab5);
- .env.example: переменные приложения и стенда lab5 + блок lab6
(OTEL_*) из skeleton.
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
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 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;
|
||||
const PURGE_BATCHES = 10;
|
||||
|
||||
@Injectable()
|
||||
export class IdempotencyRepository {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
/**
|
||||
* 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(
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
chatId: string,
|
||||
ttlSeconds: number,
|
||||
): Promise<IdempotencyRecord | undefined> {
|
||||
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 forget(
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
ttlSeconds: number,
|
||||
): 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
|
||||
AND created_at < now() - make_interval(secs => $4::double precision)`,
|
||||
[userId, path, key, ttlSeconds],
|
||||
);
|
||||
}
|
||||
|
||||
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`,
|
||||
[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: pg.PoolClient = 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(
|
||||
`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}
|
||||
)`,
|
||||
[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