import type { DbTransactionClient } from "@hivegrid/db/transactions.server"; const CHAT_MEMBERSHIP_LOCK_SALT = 15_018; const PERMISSION_GROUP_LOCK_SALT = 15_019; /** * Serializes every mutation that derives or changes one channel membership. * Callers must acquire this before loading TeamChatMember state and keep all * source reconciliation in the same transaction. */ export async function lockChatMembershipWithTx( tx: DbTransactionClient, tenantId: string, chatId: string ): Promise { const normalizedTenantId = normalizeIdentifier(tenantId, "tenantId"); const normalizedChatId = normalizeIdentifier(chatId, "chatId"); const lockKey = `chat-membership:${normalizedTenantId}:${normalizedChatId}`; await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_MEMBERSHIP_LOCK_SALT}))`; } /** * Cross-module permission-group references intentionally have no FK (AD-21). * A stable, sorted advisory-lock order therefore protects validation plus the * subsequent bare-id write from concurrent membership changes/deletion. */ export async function lockPermissionGroupsWithTx( tx: DbTransactionClient, tenantId: string, groupIds: readonly string[] ): Promise { const normalizedTenantId = normalizeIdentifier(tenantId, "tenantId"); const normalizedGroupIds = [...new Set(groupIds.map((groupId) => normalizeIdentifier(groupId, "groupId")))].sort(); for (const groupId of normalizedGroupIds) { const lockKey = `permission-group:${normalizedTenantId}:${groupId}`; await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${PERMISSION_GROUP_LOCK_SALT}))`; } return normalizedGroupIds; } function normalizeIdentifier(value: string, label: "tenantId" | "chatId" | "groupId"): string { const normalized = value.trim(); if (!normalized || normalized.length > 500 || normalized.includes("\0")) { throw new Error(`${label} is invalid`); } return normalized; }