import 'dotenv/config'; import assert from 'node:assert/strict'; import { randomUUID } from 'node:crypto'; import { createRequire } from 'node:module'; import test from 'node:test'; const require = createRequire(import.meta.url); const { NestFactory } = require('@nestjs/core'); const { AppModule } = require('../dist/app.module'); const { PrismaService } = require('../dist/prisma/prisma.service'); const { createFastifyAdapter, exposeRequestIdHeader, } = require('../dist/common/http/fastify-adapter'); test( 'message idempotency is shared by two API instances', { timeout: 120000 }, async (t) => { assert.ok( process.env.DATABASE_URL, 'Set DATABASE_URL and apply migrations', ); const apps = []; let db; let chatId; const userIds = []; t.after(async () => { if (db && chatId) { await db.$executeRawUnsafe( 'DELETE FROM message_idempotency WHERE chat_id = $1::uuid', chatId, ); await db.chat.deleteMany({ where: { id: chatId } }); } if (db && userIds.length) { await db.user.deleteMany({ where: { id: { in: userIds } } }); } for (const app of apps) await app.close(); }); for (let index = 0; index < 2; index++) { const app = await NestFactory.create(AppModule, createFastifyAdapter(), { logger: false, }); exposeRequestIdHeader(app); await app.init(); await app.getHttpAdapter().getInstance().ready(); apps.push(app); } db = apps[0].get(PrismaService); const servers = apps.map((app) => app.getHttpAdapter().getInstance()); const call = (index, method, url, token, payload, key) => servers[index].inject({ method, url, headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(key === undefined ? {} : { 'idempotency-key': key }), }, ...(payload === undefined ? {} : { payload }), }); const register = async (label) => { const username = `idem_${label}_${randomUUID().replaceAll('-', '').slice(0, 12)}`; const password = `T3st-${randomUUID()}`; const response = await call(0, 'POST', '/api/v1/users', undefined, { username, display_name: label, password, }); assert.equal(response.statusCode, 201, response.body); const user = response.json(); userIds.push(user.id); const login = await servers[0].inject({ method: 'POST', url: '/api/v1/auth/sessions', headers: { authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`, }, }); assert.equal(login.statusCode, 201, login.body); return { user, token: login.json().token }; }; const owner = await register('owner'); const outsider = await register('outsider'); const created = await call(0, 'POST', '/api/v1/chats', owner.token, { title: 'Idempotency test', member_ids: [owner.user.id], }); assert.equal(created.statusCode, 201, created.body); chatId = created.json().id; const path = `/api/v1/chats/${chatId}/messages`; const key = randomUUID(); const body = { text: 'One message' }; assert.equal( (await call(0, 'POST', path, owner.token, body)).statusCode, 400, ); assert.equal( (await call(0, 'POST', path, owner.token, body, 'bad key')).statusCode, 400, ); const first = await call(0, 'POST', path, owner.token, body, key); assert.equal(first.statusCode, 201, first.body); const replay = await call(1, 'POST', path, owner.token, body, key); assert.equal(replay.statusCode, 201, replay.body); assert.deepEqual(replay.json(), first.json()); assert.equal( (await call(1, 'POST', path, owner.token, { text: 'Changed' }, key)) .statusCode, 409, ); assert.equal( (await call(1, 'POST', path, outsider.token, body, key)).statusCode, 404, ); const concurrentKey = randomUUID(); const concurrent = await Promise.all( Array.from({ length: 12 }, (_, index) => call( index % 2, 'POST', path, owner.token, { text: 'Concurrent' }, concurrentKey, ), ), ); for (const response of concurrent) { assert.equal(response.statusCode, 201, response.body); assert.deepEqual(response.json(), concurrent[0].json()); } assert.equal(await db.message.count({ where: { chatId } }), 2); const [record] = await db.$queryRawUnsafe( 'SELECT expires_at AS "expiresAt" FROM message_idempotency WHERE user_id = $1::uuid AND chat_id = $2::uuid AND "key" = $3', owner.user.id, chatId, concurrentKey, ); assert.ok(record.expiresAt.getTime() - Date.now() >= 23 * 3600 * 1000); }, );