'use strict'; const assert = require('node:assert/strict'); const { randomUUID } = require('node:crypto'); const { pool, transaction } = require('./src/db'); const { migrate } = require('./src/migrate'); const { sendMessage } = require('./src/messages'); async function counts() { const result = {}; for (const table of ['users', 'chats', 'chat_members', 'messages', 'sessions', 'message_requests']) result[table] = (await pool.query(`SELECT count(*) AS n FROM ${table}`)).rows[0].n; return result; } async function main() { const before = await counts(); await migrate(); await migrate(); assert.deepEqual(await counts(), before); assert.equal((await pool.query('SELECT count(*)::int AS n FROM schema_migrations')).rows[0].n, 2); const user = randomUUID(), chat = randomUUID(), key = randomUUID(); await transaction(async client => { await client.query('INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)', [user, 'ttl_' + user.replaceAll('-', '').slice(0, 16), 'Synthetic TTL test', 'unusable-test-hash']); await client.query('INSERT INTO chats(id,title) VALUES($1,$2)', [chat, 'Retention test']); await client.query('INSERT INTO chat_members VALUES($1,$2)', [chat, user]); }); const first = await sendMessage(user, chat, key, 'Original'); await assert.rejects(sendMessage(user, chat, key, 'Changed'), e => e.status === 409); assert.equal((await pool.query('SELECT count(*)::int AS n FROM messages WHERE chat_id=$1', [chat])).rows[0].n, 1); const hours = (await pool.query(`SELECT extract(epoch FROM (expires_at-clock_timestamp()))/3600 AS hours FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3`, [user, chat, key])).rows[0].hours; assert.ok(Number(hours) > 23.9); // Simulate expiry only for the synthetic record, without waiting 24 hours. await pool.query(`UPDATE message_requests SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id=$1 AND chat_id=$2 AND key=$3`, [user, chat, key]); const second = await sendMessage(user, chat, key, 'After expiry'); assert.notEqual(first.id, second.id); assert.equal((await pool.query('SELECT count(*)::int AS n FROM messages WHERE chat_id=$1', [chat])).rows[0].n, 2); assert.equal((await pool.query('SELECT count(*)::int AS n FROM message_requests WHERE chat_id=$1', [chat])).rows[0].n, 1); const missingChat = randomUUID(); await assert.rejects(sendMessage(user, missingChat, randomUUID(), 'Must rollback'), e => e.code === '23503'); assert.equal((await pool.query('SELECT count(*)::int AS n FROM message_requests WHERE chat_id=$1', [missingChat])).rows[0].n, 0); console.log('PASS: migrations repeat without data changes; 24-hour retention; conflict inserts no duplicate; expired key may be reused without deleting old message; FK failure leaves no idempotency result.'); } main().catch(error => { console.error('FAIL: storage check (' + (error.code || error.name) + ')'); process.exitCode = 1; }).finally(() => pool.end());