forked from mtusi2026/mtusi2026lab3
feat: add idempotency-key
This commit is contained in:
@@ -373,6 +373,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
|
||||
const res = await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'hi', sender_id: bob.id })
|
||||
.expect(400);
|
||||
@@ -385,6 +386,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: '' })
|
||||
.expect(400);
|
||||
@@ -396,6 +398,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: ' \n\t ' })
|
||||
.expect(400);
|
||||
@@ -408,6 +411,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(eve))
|
||||
.send({ text: 'intrusion' })
|
||||
.expect(404);
|
||||
@@ -449,6 +453,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'x'.repeat(4001) })
|
||||
.expect(400);
|
||||
@@ -460,6 +465,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'x'.repeat(4000) })
|
||||
.expect(201);
|
||||
@@ -473,6 +479,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
expect([...text].length).toBe(4001);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text })
|
||||
.expect(400);
|
||||
@@ -495,6 +502,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'only message' })
|
||||
.expect(201);
|
||||
@@ -538,11 +546,13 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chatA.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'first' })
|
||||
.expect(201);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chatA.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'second' })
|
||||
.expect(201);
|
||||
@@ -569,6 +579,7 @@ describe('API мессенджера (e2e) — граничные случаи
|
||||
for (const text of sentTexts) {
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text })
|
||||
.expect(201);
|
||||
|
||||
@@ -45,6 +45,7 @@ describe('Безопасность при конкурентном доступ
|
||||
sendTasks.push(
|
||||
request(server)
|
||||
.post(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(clients[c]))
|
||||
.send({ text: `client-${c}-message-${m}` }),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user