Files
mtusi2026lab4/app/src/messages/idempotency/idempotency.ts
T

27 lines
954 B
TypeScript

import { createHash } from 'node:crypto';
// Contract: ASCII [A-Za-z0-9._:-]{1,128}. Anything else (including a duplicated
// header, which Fastify joins with ", ") is rejected as a client error.
export const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
export function messagesPath(chatId: string): string {
return `/api/v1/chats/${chatId}/messages`;
}
// The fingerprint is derived from the validated payload with a fixed field
// order, so neither JSON key order nor an absent optional field can change it.
// Text-only messages keep the lab3 fingerprint; the order of attachment ids
// is significant because it is the order of attachments in the message.
export function idempotencyFingerprint(
text: string,
attachmentIds: string[],
): string {
return createHash('sha256')
.update(
attachmentIds.length === 0
? JSON.stringify({ text })
: JSON.stringify({ text, attachment_ids: attachmentIds }),
)
.digest('hex');
}