forked from mtusi2026/mtusi2026lab3
30 lines
1.8 KiB
JavaScript
30 lines
1.8 KiB
JavaScript
'use strict';
|
|
const { randomUUID } = require('node:crypto');
|
|
const { transaction } = require('./db');
|
|
const retention = Number(process.env.IDEMPOTENCY_TTL_SECONDS || 86400);
|
|
if (!Number.isSafeInteger(retention) || retention < 86400) throw new Error('Idempotency retention must be at least 24 hours');
|
|
|
|
async function sendMessage(userId, chatId, key, text) {
|
|
return transaction(async client => {
|
|
// Shared PostgreSQL lock serializes this operation across all API replicas.
|
|
// Hash collisions only serialize unrelated keys; the actual lookup uses the full scope.
|
|
const scope = JSON.stringify([userId, chatId, key]);
|
|
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [scope]);
|
|
await client.query(`DELETE FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3
|
|
AND expires_at <= clock_timestamp()`, [userId, chatId, key]);
|
|
const prior = await client.query('SELECT text,response FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3', [userId, chatId, key]);
|
|
if (prior.rowCount) {
|
|
if (prior.rows[0].text !== text) throw Object.assign(new Error('Key already used for another message'), { status: 409, code: 'conflict' });
|
|
return prior.rows[0].response;
|
|
}
|
|
const message = (await client.query(`INSERT INTO messages(id,chat_id,sender_id,text)
|
|
VALUES($1,$2,$3,$4) RETURNING *`, [randomUUID(), chatId, userId, text])).rows[0];
|
|
await client.query(`INSERT INTO message_requests(user_id,chat_id,key,text,message_id,response,expires_at)
|
|
VALUES($1,$2,$3,$4,$5,$6::jsonb,clock_timestamp()+$7*interval '1 second')`,
|
|
[userId, chatId, key, text, message.id, JSON.stringify(message), retention]);
|
|
// The HTTP handler returns 201 only after transaction() completes COMMIT.
|
|
return message;
|
|
});
|
|
}
|
|
module.exports = { sendMessage };
|