import 'dotenv/config'; import assert from 'node:assert/strict'; import { createHash, randomBytes, 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 keyset pagination: timestamp ties, chat isolation and deleted cursor row', async (t) => { assert.ok(process.env.DATABASE_URL); const previousCacheUrl = process.env.CACHE_URL; process.env.CACHE_URL = ''; const app = await NestFactory.create(AppModule, createFastifyAdapter(), { logger: false, abortOnError: false, }); const prisma = app.get(PrismaService); let userId; const chatIds = []; t.after(async () => { try { await prisma.chat.deleteMany({ where: { id: { in: chatIds } } }); if (userId) await prisma.user.delete({ where: { id: userId } }); } finally { await app.close(); if (previousCacheUrl === undefined) delete process.env.CACHE_URL; else process.env.CACHE_URL = previousCacheUrl; } }); exposeRequestIdHeader(app); await app.init(); const server = app.getHttpAdapter().getInstance(); await server.ready(); const user = await prisma.user.create({ data: { username: `page_${randomUUID().replaceAll('-', '').slice(0, 20)}`, displayName: 'Synthetic pagination test', }, }); userId = user.id; const token = randomBytes(32).toString('base64url'); await prisma.session.create({ data: { userId, tokenHash: createHash('sha256').update(token).digest('hex'), expiresAt: new Date(Date.now() + 600000), }, }); for (let i = 0; i < 2; i++) { const chat = await prisma.chat.create({ data: { title: `Pagination ${i}`, members: { create: { userId, position: 0 } }, }, }); chatIds.push(chat.id); } const [chatId, otherChatId] = chatIds; const rows = Array.from({ length: 140 }, (_, i) => ({ id: randomUUID(), chatId, senderId: userId, text: `Message ${i}`, createdAt: new Date(Date.UTC(2026, 0, 1) + Math.floor(i / 10) * 1000), })); await prisma.message.createMany({ data: [ ...rows, ...rows.map((row) => ({ ...row, id: randomUUID(), chatId: otherChatId, text: 'Other chat', })), ], }); const expected = [...rows] .sort( (a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0), ) .map((row) => ({ id: row.id, chat_id: chatId, sender_id: userId, text: row.text, created_at: row.createdAt.toISOString(), })); const request = (cursor, selectedChat = chatId) => server.inject({ method: 'GET', url: `/api/v1/chats/${selectedChat}/messages?limit=7${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`, headers: { authorization: `Bearer ${token}` }, }); const seen = []; let cursor; let firstCursor; do { const response = await request(cursor); assert.equal(response.statusCode, 200); const page = response.json(); assert.ok(page.items.length <= 7); seen.push(...page.items); if (!firstCursor) firstCursor = page.next_cursor; cursor = page.next_cursor; assert.ok( seen.length <= rows.length, 'pagination must terminate without duplicates', ); } while (cursor); assert.deepEqual(seen, expected); const anchor = JSON.parse( Buffer.from(firstCursor, 'base64url').toString('utf8'), ); await prisma.message.delete({ where: { id: anchor.id } }); const afterDeletion = await request(firstCursor); assert.equal(afterDeletion.statusCode, 200); assert.deepEqual(afterDeletion.json().items, expected.slice(7, 14)); assert.equal((await request(firstCursor, otherChatId)).statusCode, 400); const pastEnd = Buffer.from( JSON.stringify({ scope: `messages:${chatId}`, id: randomUUID(), created_at: '2027-01-01T00:00:00.000Z', }), ).toString('base64url'); const empty = await request(pastEnd); assert.equal(empty.statusCode, 200); assert.deepEqual(empty.json(), { items: [], next_cursor: null }); });