import { INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { FastifyAdapter, NestFastifyApplication, } from '@nestjs/platform-fastify'; import request from 'supertest'; import { randomUUID } from 'crypto'; import { AppModule } from '../src/app.module'; import { configureApp } from '../src/configure-app'; describe('Безопасность при конкурентном доступе (e2e)', () => { let app: INestApplication; let server: any; beforeAll(async () => { const moduleRef = await Test.createTestingModule({ imports: [AppModule], }).compile(); const fastifyApp = moduleRef.createNestApplication( new FastifyAdapter(), ); app = fastifyApp; configureApp(fastifyApp); await fastifyApp.listen(0, '127.0.0.1'); server = fastifyApp.getHttpServer(); }); afterAll(async () => { await app.close(); }); it('принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных', async () => { const CLIENTS = 10; const MESSAGES_PER_CLIENT = 10; const owner = await request(server) .post('/api/v1/users') .send({ username: `owner_${randomUUID().slice(0, 8)}`, display_name: 'Owner', }) .expect(201); const clients = await Promise.all( Array.from({ length: CLIENTS }, (_, i) => request(server) .post('/api/v1/users') .send({ username: `racer${i}_${randomUUID().slice(0, 6)}`, display_name: `Racer ${i}`, }) .expect(201), ), ); const memberIds = [owner.body.id, ...clients.map((c) => c.body.id)]; const chat = await request(server) .post('/api/v1/chats') .set('X-User-Id', owner.body.id) .send({ title: 'Race', member_ids: memberIds }) .expect(201); const sendTasks: Promise[] = []; for (let c = 0; c < CLIENTS; c++) { for (let m = 0; m < MESSAGES_PER_CLIENT; m++) { sendTasks.push( request(server) .post(`/api/v1/chats/${chat.body.id}/messages`) .set('X-User-Id', clients[c].body.id) .send({ text: `client-${c}-message-${m}` }), ); } } const responses = await Promise.all(sendTasks); for (const res of responses) { expect(res.status).toBe(201); } const sentIds = new Set(responses.map((r) => r.body.id)); expect(sentIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT); const collected: { id: string; text: string }[] = []; let cursor: string | null = null; do { const res: request.Response = await request(server) .get(`/api/v1/chats/${chat.body.id}/messages`) .query({ limit: 25, ...(cursor ? { cursor } : {}) }) .set('X-User-Id', owner.body.id) .expect(200); collected.push(...res.body.items); cursor = res.body.next_cursor; } while (cursor); expect(collected.length).toBe(CLIENTS * MESSAGES_PER_CLIENT); const uniqueIds = new Set(collected.map((m) => m.id)); expect(uniqueIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT); const uniqueTexts = new Set(collected.map((m) => m.text)); expect(uniqueTexts.size).toBe(CLIENTS * MESSAGES_PER_CLIENT); const fullHistory: { id: string; created_at: string }[] = await request(server) .get(`/api/v1/chats/${chat.body.id}/messages`) .query({ limit: 100 }) .set('X-User-Id', owner.body.id) .expect(200) .then((res) => res.body.items); const sortKeys = fullHistory.map((m) => `${m.created_at}#${m.id}`); const sortedKeys = [...sortKeys].sort(); expect(sortKeys).toEqual(sortedKeys); }); it('регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username', async () => { const username = `racer_username_${randomUUID().slice(0, 8)}`; const attempts = 10; const responses = await Promise.all( Array.from({ length: attempts }, () => request(server) .post('/api/v1/users') .send({ username, display_name: 'Racer' }), ), ); const succeeded = responses.filter((r) => r.status === 201); const conflicted = responses.filter((r) => r.status === 409); expect(succeeded.length).toBe(1); expect(conflicted.length).toBe(attempts - 1); expect(succeeded.length + conflicted.length).toBe(attempts); const listRes = await request(server) .get('/api/v1/users/me') .set('X-User-Id', succeeded[0].body.id) .expect(200); expect(listRes.body.username).toBe(username); }); });