forked from mtusi2026/mtusi2026lab3
140 lines
5.8 KiB
TypeScript
140 lines
5.8 KiB
TypeScript
import { INestApplication } from '@nestjs/common';
|
|
import request from 'supertest';
|
|
import { randomUUID } from 'crypto';
|
|
import { PrismaService } from '../src/db/prisma.service';
|
|
import { bearer, createTestApp, registerUser, TestUser } from './helpers';
|
|
|
|
function sleep(ms: number): Promise<void> {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
describe('Идемпотентность отправки и X-Instance-Id (e2e)', () => {
|
|
const apps: INestApplication[] = [];
|
|
let server: any;
|
|
let replica: any;
|
|
let prisma: PrismaService;
|
|
|
|
beforeAll(async () => {
|
|
const first = await createTestApp();
|
|
const second = await createTestApp();
|
|
apps.push(first.app, second.app);
|
|
server = first.server;
|
|
replica = second.server;
|
|
prisma = first.app.get(PrismaService);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await Promise.all(apps.map((app) => app.close()));
|
|
});
|
|
|
|
async function setup(label: string) {
|
|
const alice = await registerUser(server, label);
|
|
const chat = await request(server)
|
|
.post('/api/v1/chats')
|
|
.set('Authorization', bearer(alice))
|
|
.send({ title: 'Idem', member_ids: [alice.id] })
|
|
.expect(201);
|
|
return { alice, path: `/api/v1/chats/${chat.body.id}/messages` };
|
|
}
|
|
|
|
function send(target: any, user: TestUser, path: string, key: string | null, body: object) {
|
|
const req = request(target).post(path).set('Authorization', bearer(user));
|
|
return (key === null ? req : req.set('Idempotency-Key', key)).send(body);
|
|
}
|
|
|
|
async function countMessages(path: string, user: TestUser): Promise<number> {
|
|
const res = await request(server)
|
|
.get(`${path}?limit=100`)
|
|
.set('Authorization', bearer(user))
|
|
.expect(200);
|
|
return res.body.items.length;
|
|
}
|
|
|
|
it('требует Idempotency-Key правильного формата', async () => {
|
|
const { alice, path } = await setup('keyfmt');
|
|
for (const key of [null, '', 'has space', 'semi;colon', 'slash/key', 'x'.repeat(129)]) {
|
|
const res = await send(server, alice, path, key, { text: 'x' });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.code).toBe('invalid_request');
|
|
}
|
|
await send(server, alice, path, 'A-z_0.9:' + 'k'.repeat(120), { text: 'x' }).expect(201);
|
|
});
|
|
|
|
it('повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение', async () => {
|
|
const { alice, path } = await setup('replay');
|
|
const key = randomUUID();
|
|
const first = await send(server, alice, path, key, { text: 'Привет 👋' }).expect(201);
|
|
const again = await send(replica, alice, path, key, { text: 'Привет 👋' }).expect(201);
|
|
expect(again.body).toEqual(first.body);
|
|
expect(await countMessages(path, alice)).toBe(1);
|
|
});
|
|
|
|
it('тот же ключ с другим телом — 409, сообщение не создаётся', async () => {
|
|
const { alice, path } = await setup('conflict');
|
|
const key = randomUUID();
|
|
await send(server, alice, path, key, { text: 'первое' }).expect(201);
|
|
const res = await send(server, alice, path, key, { text: 'другое' }).expect(409);
|
|
expect(res.body.error.code).toBe('conflict');
|
|
expect(await countMessages(path, alice)).toBe(1);
|
|
});
|
|
|
|
it('20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение', async () => {
|
|
const { alice, path } = await setup('parallel');
|
|
const key = randomUUID();
|
|
const responses = await Promise.all(
|
|
Array.from({ length: 20 }, (_, i) =>
|
|
send(i % 2 ? replica : server, alice, path, key, { text: 'одно' }),
|
|
),
|
|
);
|
|
expect(responses.map((r) => r.status)).toEqual(Array(20).fill(201));
|
|
expect(new Set(responses.map((r) => r.body.id)).size).toBe(1);
|
|
expect(await countMessages(path, alice)).toBe(1);
|
|
});
|
|
|
|
it('область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим', async () => {
|
|
const a = await setup('scopea');
|
|
const b = await setup('scopeb');
|
|
const key = randomUUID();
|
|
const one = await send(server, a.alice, a.path, key, { text: 'x' }).expect(201);
|
|
const two = await send(server, b.alice, b.path, key, { text: 'x' }).expect(201);
|
|
expect(one.body.id).not.toBe(two.body.id);
|
|
});
|
|
|
|
it('повтор заново проверяет сессию', async () => {
|
|
const { alice, path } = await setup('recheck');
|
|
const key = randomUUID();
|
|
await send(server, alice, path, key, { text: 'x' }).expect(201);
|
|
await request(server)
|
|
.delete('/api/v1/auth/sessions/current')
|
|
.set('Authorization', bearer(alice))
|
|
.expect(204);
|
|
await send(server, alice, path, key, { text: 'x' }).expect(401);
|
|
});
|
|
|
|
it('после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново', async () => {
|
|
const { app, server: short } = await createTestApp({ IDEMPOTENCY_TTL_SECONDS: '1' });
|
|
apps.push(app);
|
|
const { alice, path } = await setup('ttl');
|
|
const key = randomUUID();
|
|
const first = await send(short, alice, path, key, { text: 'x' }).expect(201);
|
|
await sleep(1500);
|
|
const second = await send(short, alice, path, key, { text: 'y' }).expect(201);
|
|
expect(second.body.id).not.toBe(first.body.id);
|
|
expect(await prisma.idempotencyKey.count({ where: { key } })).toBe(1);
|
|
});
|
|
|
|
it('X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе', async () => {
|
|
const ids = new Set<string>();
|
|
for (const res of [
|
|
await request(server).get('/health/live').expect(200),
|
|
await request(server).get('/health/ready').expect(200),
|
|
await request(server).get('/api/v1/users/me').expect(401),
|
|
await request(server).post('/api/v1/users').send('{bad').set('Content-Type', 'application/json').expect(400),
|
|
]) {
|
|
expect(res.headers['x-instance-id']).toBeTruthy();
|
|
ids.add(res.headers['x-instance-id']);
|
|
}
|
|
expect(ids.size).toBe(1);
|
|
});
|
|
});
|