lab5: базовый коммит из lab4 (abba248)

Перенесено дерево lab4 целиком: NestJS-приложение с вложениями и S3,
Dockerfile, compose.yaml, infra/{haproxy,minio}, стендовые скрипты,
scripts/lab4, evidence/lab4 и contracts/extensions.openapi.json.

Задание lab5 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,examples},
tests, compose.example.yaml, .github/pull_request_template.md.

Адаптации при переносе:
- docker-проект mtusi-lab4 -> mtusi-lab5 и тег образа mtusi-messenger:lab5,
  чтобы тома и контейнеры не пересекались с lab4 (scripts/stop-one.sh:
  LAB_PROJECT вместо LAB4_PROJECT);
- Makefile: цели lab5 сохранены, добавлены стендовые (stand-up/down,
  wait-ready, init-env, test-e2e, test-dependencies, s3-security,
  consistency, bench);
- .env.example: реальные переменные приложения и стенда lab4 (без них
  compose.yaml не поднимается) + блок lab5 (BROKER_URL_FILE, WORKER_*).
This commit is contained in:
2026-11-04 23:44:11 +03:00
parent 276dbdad8a
commit 1982bdb690
153 changed files with 21742 additions and 11 deletions
@@ -0,0 +1,33 @@
import { fileURLToPath } from 'node:url';
import { parseDatabaseConfig } from '../../config/app-config.schema.js';
import { DatabaseClient } from '../../database/database.client.js';
import { MetricsService } from '../../metrics/metrics.service.js';
import { IdempotencyRepository } from './idempotency.repository.js';
// Manual operator pass over the idempotency ledger: the API also purges expired
// claims in the background, but an operator must be able to reclaim space
// without waiting for traffic. It never touches unexpired claims.
// in the stand: docker compose exec api node dist/messages/idempotency/idempotency-gc.cli.js
// on the host: npm run idempotency:gc (needs a reachable DATABASE_URL)
async function main(): Promise<void> {
const config = parseDatabaseConfig(process.env as Record<string, unknown>);
const database = new DatabaseClient(
{
getOrThrow: (key: keyof typeof config) => config[key],
} as never,
new MetricsService(),
);
try {
const repository = new IdempotencyRepository(database);
const purged = await repository.purgeExpired(
config.IDEMPOTENCY_TTL_SECONDS,
);
process.stdout.write(
`Purged ${purged} idempotency key(s) older than ${config.IDEMPOTENCY_TTL_SECONDS} seconds\n`,
);
} finally {
await database.onModuleDestroy();
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../../database/database.module.js';
import { IdempotencyRepository } from './idempotency.repository.js';
@Module({
imports: [DatabaseModule],
providers: [IdempotencyRepository],
exports: [IdempotencyRepository],
})
export class IdempotencyModule {}
@@ -0,0 +1,24 @@
import { describe, expect, it, vi } from 'vitest';
import { IdempotencyRepository } from './idempotency.repository.js';
describe('IdempotencyRepository expired-key cleanup', () => {
it('deletes only rows older than the configured TTL', async () => {
const query = vi.fn().mockResolvedValue({ rowCount: 0, rows: [] });
const repository = new IdempotencyRepository({ query } as never);
await repository.forget(
'user',
'/api/v1/chats/chat/messages',
'key',
86400,
);
expect(query).toHaveBeenCalledWith(
'idempotency.forget',
expect.stringContaining(
'created_at < now() - make_interval(secs => $4::double precision)',
),
['user', '/api/v1/chats/chat/messages', 'key', 86400],
);
});
});
@@ -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();
}
}
}
@@ -0,0 +1,26 @@
import { createHash } from 'node:crypto';
// Contract: ASCII [A-Za-z0-9._:-]{1,128}. Anything else (including a duplicated
// header, which Fastify joins with ", ") is rejected as a client error.
export const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
export function messagesPath(chatId: string): string {
return `/api/v1/chats/${chatId}/messages`;
}
// The fingerprint is derived from the validated payload with a fixed field
// order, so neither JSON key order nor an absent optional field can change it.
// Text-only messages keep the lab3 fingerprint; the order of attachment ids
// is significant because it is the order of attachments in the message.
export function idempotencyFingerprint(
text: string,
attachmentIds: string[],
): string {
return createHash('sha256')
.update(
attachmentIds.length === 0
? JSON.stringify({ text })
: JSON.stringify({ text, attachment_ids: attachmentIds }),
)
.digest('hex');
}