2006 lines
79 KiB
TypeScript
2006 lines
79 KiB
TypeScript
import { getWriteDbClient } from "@hivegrid/db/client.server";
|
|
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
|
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
|
|
import { featureKeys } from "@hivegrid/entitlements";
|
|
import { CatalogError, foundationErrors, notify, withPermission, withTenantScope } from "@hivegrid/foundation";
|
|
import {
|
|
CHAT_EVENT_NAMES,
|
|
extractChatMentions,
|
|
isPersistentChatEvent,
|
|
normalizeChatEventCursor,
|
|
normalizeChatResumeCursor,
|
|
parseChatResumeCursor,
|
|
validateChatServerEvent,
|
|
type ChatMention,
|
|
type ChatLinkPreview,
|
|
type ChatPersistentEvent,
|
|
type ChatRealtimeMessage,
|
|
} from "@hivegrid/realtime";
|
|
|
|
import { toChatPersistentEventName, toPersistedChatEventType } from "./event-type-mapping.js";
|
|
import { buildChatMessageDeepLink } from "./deep-links.js";
|
|
import { chatErrors } from "./errors.js";
|
|
import { extractChatLinkPreviewPlaceholders, publishChatLinkPreviewRequest } from "./link-preview.server.js";
|
|
import { resolveChatMentionsInBodyWithTx } from "./mentions.server.js";
|
|
import { publishTopLevelChatMessageEffectsWithTx } from "./message-effects.server.js";
|
|
import { tenantHasChatModuleWithPermissionsTx, tenantHasFilesModuleWithPermissionsTx } from "./module-access.server.js";
|
|
import { CHAT_PERMISSIONS } from "./permissions.js";
|
|
import { publishChatPersistentRealtimeWakeup } from "./realtime-wakeup.server.js";
|
|
import type {
|
|
ChatEventGapResult,
|
|
ChatAttachmentRecord,
|
|
ChatMemberChannelDetail,
|
|
ChatMemberChannelListView,
|
|
ChatMemberChannelRecord,
|
|
ChatMessageReadReceiptRecord,
|
|
ChatMessageFeatureRecord,
|
|
ChatParticipantProfileRecord,
|
|
ChatRepositoryContext,
|
|
FillChatEventGapInput,
|
|
GetMemberChannelDetailInput,
|
|
GetChatMessageTaskSourceInput,
|
|
ChatMessageTaskSourceRecord,
|
|
WithWritableChatMessageTaskSourceInput,
|
|
ListMemberChannelsInput,
|
|
ListMemberChannelsResult,
|
|
MarkChatMessageReadInput,
|
|
MarkChatMessageReadResult,
|
|
RevalidateChatGatewayAccessInput,
|
|
SendTopLevelChatMessageInput,
|
|
SendTopLevelChatMessageResult,
|
|
} from "./types.js";
|
|
|
|
const ACTIVE_TENANT_USER_STATUS = 2;
|
|
const DEFAULT_CHANNEL_LIMIT = 50;
|
|
const MAX_CHANNEL_LIMIT = 100;
|
|
const DEFAULT_MESSAGE_LIMIT = 50;
|
|
const MAX_MESSAGE_LIMIT = 100;
|
|
const DEFAULT_EVENT_GAP_LIMIT = 100;
|
|
const MAX_EVENT_GAP_LIMIT = 250;
|
|
const CHAT_EVENT_LOCK_SALT = 15_015;
|
|
const MAX_GATEWAY_REVALIDATION_CHAT_IDS = 64;
|
|
const MAX_CHANNEL_QUERY_LENGTH = 200;
|
|
const MAX_CHANNEL_CURSOR_LENGTH = 2_048;
|
|
const MAX_MESSAGE_CURSOR_LENGTH = 2_048;
|
|
const MEMBER_CHANNEL_LIST_VIEWS = new Set<ChatMemberChannelListView>(["all", "unread", "mentions", "pinned", "projects", "groups", "direct"]);
|
|
|
|
type PersistedMessageRow = {
|
|
id: string;
|
|
createdAt: Date;
|
|
updatedAt: Date;
|
|
tenantId: string;
|
|
chatId: string;
|
|
authorUserId: string | null;
|
|
clientMessageId: string;
|
|
body: string;
|
|
bodyFormat: "markdown" | "system";
|
|
parentMessageId: string | null;
|
|
mentions: unknown;
|
|
linkPreviews: unknown;
|
|
editedAt: Date | null;
|
|
deletedAt: Date | null;
|
|
deletedByUserId: string | null;
|
|
systemEventKind: string | null;
|
|
systemEventMetadata: unknown;
|
|
};
|
|
|
|
type PersistedMemberChannelRow = {
|
|
id: string;
|
|
kind: "project" | "group" | "dm";
|
|
name: string | null;
|
|
description: string | null;
|
|
projektId: string | null;
|
|
isPrivate: boolean;
|
|
archivedAt: Date | null;
|
|
lastMessageAt: Date | null;
|
|
eventStreamId: string;
|
|
members: Array<{
|
|
roleInChat: "admin" | "member";
|
|
notificationPref: "all_messages" | "mentions_only" | "muted";
|
|
lastReadMessageId: string | null;
|
|
lastReadAt: Date | null;
|
|
isPinned: boolean;
|
|
writeRevokedAt: Date | null;
|
|
}>;
|
|
_count: { members: number };
|
|
messages?: PersistedMessageRow[];
|
|
};
|
|
|
|
type PersistedEventRow = {
|
|
sequence: bigint;
|
|
occurredAt: Date;
|
|
tenantId: string;
|
|
chatId: string;
|
|
type: Parameters<typeof toChatPersistentEventName>[0];
|
|
actorUserId: string | null;
|
|
entityId: string | null;
|
|
requestId: string;
|
|
data: unknown;
|
|
};
|
|
|
|
type PersistedAttachmentRow = ChatAttachmentRecord;
|
|
|
|
type ParticipantProfileProjectionRow = {
|
|
chatId: string;
|
|
userId: string;
|
|
displayName: string;
|
|
avatarUrl: string | null;
|
|
};
|
|
|
|
type UnreadProjectionRow = {
|
|
chatId: string;
|
|
unreadCount: number;
|
|
hasUnreadMention: boolean;
|
|
};
|
|
|
|
type MessageCursor = {
|
|
readonly createdAt: Date;
|
|
readonly id: string;
|
|
};
|
|
|
|
type MemberChannelSortRow = {
|
|
readonly chatId: string;
|
|
readonly isPinned: boolean;
|
|
readonly lastMessageAt: Date | null;
|
|
readonly createdAt: Date;
|
|
};
|
|
|
|
type MemberChannelCandidateRow = MemberChannelSortRow & {
|
|
readonly eventStreamId: string;
|
|
readonly latestEventSequence: bigint | null;
|
|
readonly unreadCount: number;
|
|
readonly hasUnreadMention: boolean;
|
|
};
|
|
|
|
type MemberChannelCursor = MemberChannelSortRow & {
|
|
readonly filterKey: string;
|
|
};
|
|
|
|
type NormalizedMemberChannelListInput = {
|
|
readonly query: string;
|
|
readonly view: ChatMemberChannelListView;
|
|
readonly includeArchived: boolean;
|
|
readonly limit: number;
|
|
readonly afterCursor: MemberChannelCursor | null;
|
|
readonly filterKey: string;
|
|
};
|
|
|
|
type UnreadProjection = {
|
|
readonly unreadCount: number;
|
|
readonly hasUnreadMention: boolean;
|
|
};
|
|
|
|
const EMPTY_UNREAD_PROJECTION: UnreadProjection = {
|
|
unreadCount: 0,
|
|
hasUnreadMention: false,
|
|
};
|
|
|
|
const CHAT_MESSAGE_SELECT = {
|
|
id: true,
|
|
createdAt: true,
|
|
updatedAt: true,
|
|
tenantId: true,
|
|
chatId: true,
|
|
authorUserId: true,
|
|
clientMessageId: true,
|
|
body: true,
|
|
bodyFormat: true,
|
|
parentMessageId: true,
|
|
mentions: true,
|
|
linkPreviews: true,
|
|
editedAt: true,
|
|
deletedAt: true,
|
|
deletedByUserId: true,
|
|
systemEventKind: true,
|
|
systemEventMetadata: true,
|
|
} as const satisfies Prisma.TeamChatMessageSelect;
|
|
|
|
const CHAT_EVENT_SELECT = {
|
|
sequence: true,
|
|
occurredAt: true,
|
|
tenantId: true,
|
|
chatId: true,
|
|
type: true,
|
|
actorUserId: true,
|
|
entityId: true,
|
|
requestId: true,
|
|
data: true,
|
|
} as const satisfies Prisma.TeamChatEventSelect;
|
|
|
|
async function listMemberChannelsInternal(input: ListMemberChannelsInput): Promise<ListMemberChannelsResult> {
|
|
const normalized = mapPublicInput(() => normalizeMemberChannelListInput(input));
|
|
|
|
return runChatTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
|
|
const candidateRows = await listMemberChannelCandidates(tx, input, normalized);
|
|
const hasMore = candidateRows.length > normalized.limit;
|
|
const pageCandidates = candidateRows.slice(0, normalized.limit);
|
|
if (pageCandidates.length === 0) return { channels: [], nextCursor: null };
|
|
|
|
const pageChatIds = pageCandidates.map((candidate) => candidate.chatId);
|
|
const memberScope = withTenantScope(input.tenantId, { userId: input.userId, leftAt: null });
|
|
const hydratedRows = await tx.teamChat.findMany({
|
|
where: withTenantScope(input.tenantId, {
|
|
id: { in: pageChatIds },
|
|
members: { some: memberScope },
|
|
}),
|
|
select: {
|
|
id: true,
|
|
kind: true,
|
|
name: true,
|
|
description: true,
|
|
projektId: true,
|
|
isPrivate: true,
|
|
archivedAt: true,
|
|
lastMessageAt: true,
|
|
eventStreamId: true,
|
|
members: {
|
|
where: memberScope,
|
|
take: 1,
|
|
select: {
|
|
roleInChat: true,
|
|
notificationPref: true,
|
|
lastReadMessageId: true,
|
|
lastReadAt: true,
|
|
isPinned: true,
|
|
writeRevokedAt: true,
|
|
},
|
|
},
|
|
_count: { select: { members: { where: withTenantScope(input.tenantId, { leftAt: null }) } } },
|
|
messages: {
|
|
where: withTenantScope(input.tenantId, {
|
|
parentMessageId: null,
|
|
chat: memberChannelRelation(input),
|
|
}),
|
|
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
|
take: 1,
|
|
select: CHAT_MESSAGE_SELECT,
|
|
},
|
|
},
|
|
});
|
|
const rowsById = new Map(hydratedRows.map((row) => [row.id, row]));
|
|
const rows = mapPersistedData(() =>
|
|
pageCandidates.map((candidate) => {
|
|
const row = rowsById.get(candidate.chatId);
|
|
if (!row || row.members.length !== 1) throw new Error("Channel candidate could not be hydrated");
|
|
return row;
|
|
})
|
|
);
|
|
const participantsByChatId = groupParticipantProfiles(await listChannelListParticipantProfiles(tx, input, rows));
|
|
const latestMessageIds = rows.flatMap((row) => row.messages?.map((message) => message.id) ?? []);
|
|
const attachmentIdsByMessageId = groupAttachmentIds(await listMessageAttachmentRecords(tx, input.tenantId, latestMessageIds));
|
|
const unreadByChatId = mapUnreadProjections(
|
|
pageCandidates.map((candidate) => ({
|
|
chatId: candidate.chatId,
|
|
unreadCount: candidate.unreadCount,
|
|
hasUnreadMention: candidate.hasUnreadMention,
|
|
}))
|
|
);
|
|
|
|
return {
|
|
channels: rows.map((row, index) => {
|
|
const candidate = pageCandidates[index]!;
|
|
return mapMemberChannel(
|
|
row,
|
|
row.messages[0] ?? null,
|
|
participantsByChatId.get(row.id) ?? [],
|
|
unreadByChatId.get(row.id) ?? EMPTY_UNREAD_PROJECTION,
|
|
mapCandidateEventCursor(candidate, row.eventStreamId),
|
|
row.messages?.[0] ? (attachmentIdsByMessageId.get(row.messages[0].id) ?? []) : []
|
|
);
|
|
}),
|
|
nextCursor: hasMore ? encodeMemberChannelCursor(normalized.filterKey, pageCandidates[pageCandidates.length - 1]!) : null,
|
|
};
|
|
});
|
|
}
|
|
|
|
async function getMemberChannelDetailInternal(input: GetMemberChannelDetailInput): Promise<ChatMemberChannelDetail> {
|
|
const { chatId, messageLimit, beforeMessageCursor, focusMessageId } = mapPublicInput(() => {
|
|
const chatId = normalizeRequiredIdentifier(input.chatId, "chatId");
|
|
const focusMessageId = input.focusMessageId ? normalizeRequiredIdentifier(input.focusMessageId, "focusMessageId") : null;
|
|
if (focusMessageId && input.beforeMessageCursor) throw new Error("focusMessageId and beforeMessageCursor are mutually exclusive");
|
|
return {
|
|
chatId,
|
|
messageLimit: normalizeLimit(input.messageLimit, DEFAULT_MESSAGE_LIMIT, MAX_MESSAGE_LIMIT, "message limit"),
|
|
beforeMessageCursor: parseMessageCursor(input.beforeMessageCursor, chatId),
|
|
focusMessageId,
|
|
};
|
|
});
|
|
|
|
return runChatTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
|
|
await lockActiveChatMembership(tx, input, chatId);
|
|
const channel = await requireReadableChannel(tx, input, chatId);
|
|
const participantRows = await listParticipantProfiles(tx, input, [chatId]);
|
|
const participants = groupParticipantProfiles(participantRows).get(chatId) ?? [];
|
|
const unread = mapUnreadProjections(await listUnreadProjections(tx, input, [chatId])).get(chatId) ?? EMPTY_UNREAD_PROJECTION;
|
|
// Capture the resume boundary before reading history. A concurrent commit
|
|
// may then appear in both history and a later gap-fill, which the stable
|
|
// client id safely reconciles; it can never be skipped behind the cursor.
|
|
const latestEvent = await tx.teamChatEvent.findFirst({
|
|
where: withTenantScope(input.tenantId, { chatId, chat: memberChannelRelation(input) }),
|
|
orderBy: { sequence: "desc" },
|
|
select: { sequence: true },
|
|
});
|
|
const focusMessage = focusMessageId
|
|
? await tx.teamChatMessage.findFirst({
|
|
where: withTenantScope(input.tenantId, {
|
|
id: focusMessageId,
|
|
chatId,
|
|
parentMessageId: null,
|
|
chat: memberChannelRelation(input),
|
|
}),
|
|
select: { id: true, createdAt: true },
|
|
})
|
|
: null;
|
|
if (focusMessageId && !focusMessage) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "message-not-visible" });
|
|
}
|
|
const messageBoundary = beforeMessageCursor ?? focusMessage;
|
|
const rows = await tx.teamChatMessage.findMany({
|
|
where: withTenantScope(input.tenantId, {
|
|
chatId,
|
|
parentMessageId: null,
|
|
chat: memberChannelRelation(input),
|
|
...(messageBoundary
|
|
? {
|
|
OR: [
|
|
{ createdAt: { lt: messageBoundary.createdAt } },
|
|
{
|
|
createdAt: messageBoundary.createdAt,
|
|
id: focusMessage ? { lte: messageBoundary.id } : { lt: messageBoundary.id },
|
|
},
|
|
],
|
|
}
|
|
: {}),
|
|
}),
|
|
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
|
take: messageLimit + 1,
|
|
select: CHAT_MESSAGE_SELECT,
|
|
});
|
|
const hasOlderMessages = rows.length > messageLimit;
|
|
const visibleRows = rows.slice(0, messageLimit).reverse();
|
|
const messageIds = visibleRows.map((message) => message.id);
|
|
const participantUserIds = participants.map((participant) => participant.userId);
|
|
const readRows =
|
|
messageIds.length > 0 && participantUserIds.length > 0
|
|
? await tx.teamChatRead.findMany({
|
|
where: withTenantScope(input.tenantId, {
|
|
messageId: { in: messageIds },
|
|
userId: { in: participantUserIds },
|
|
message: {
|
|
chatId,
|
|
chat: memberChannelRelation(input),
|
|
},
|
|
}),
|
|
orderBy: [{ readAt: "asc" }, { messageId: "asc" }, { userId: "asc" }],
|
|
select: { messageId: true, userId: true, readAt: true },
|
|
})
|
|
: [];
|
|
const messageFeatures = await listMessageFeatureRecords(tx, input, chatId, messageIds);
|
|
const attachmentMessageIds = [...new Set([...messageIds, ...(channel.messages?.[0] ? [channel.messages[0].id] : [])])];
|
|
const allAttachmentRecords = await listMessageAttachmentRecords(tx, input.tenantId, attachmentMessageIds);
|
|
const attachments = allAttachmentRecords.filter((attachment) => messageIds.includes(attachment.messageId));
|
|
const attachmentIdsByMessageId = groupAttachmentIds(allAttachmentRecords);
|
|
|
|
const eventCursor = latestEvent ? mapPersistedCursor(channel.eventStreamId, latestEvent.sequence) : "0";
|
|
return {
|
|
channel: mapMemberChannel(
|
|
channel,
|
|
channel.messages?.[0] ?? null,
|
|
participants,
|
|
unread,
|
|
eventCursor,
|
|
channel.messages?.[0] ? (attachmentIdsByMessageId.get(channel.messages[0].id) ?? []) : []
|
|
),
|
|
messages: visibleRows.map((message) => mapMessage(message, channel.eventStreamId, attachmentIdsByMessageId.get(message.id) ?? [])),
|
|
readReceipts: readRows.map(mapReadReceipt),
|
|
messageFeatures,
|
|
attachments,
|
|
hasOlderMessages,
|
|
olderMessageCursor: hasOlderMessages && visibleRows[0] ? encodeMessageCursor(chatId, visibleRows[0]) : null,
|
|
eventCursor,
|
|
};
|
|
});
|
|
}
|
|
|
|
export async function listMessageAttachmentRecords(
|
|
tx: DbTransactionClient,
|
|
tenantId: string,
|
|
messageIds: readonly string[]
|
|
): Promise<PersistedAttachmentRow[]> {
|
|
if (messageIds.length === 0) return [];
|
|
const links = await tx.fileEntityLink.findMany({
|
|
where: withTenantScope(tenantId, {
|
|
entityType: "chat_message" as const,
|
|
entityId: { in: [...messageIds] },
|
|
file: { tenantId, archivedAt: null },
|
|
}),
|
|
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
|
select: {
|
|
entityId: true,
|
|
linkRole: true,
|
|
fileId: true,
|
|
},
|
|
});
|
|
const files = await tx.file.findMany({
|
|
where: withTenantScope(tenantId, { id: { in: links.map((link) => link.fileId) }, archivedAt: null }),
|
|
select: { id: true, displayName: true, mimeType: true, sizeBytes: true, previewStatus: true, scanStatus: true },
|
|
});
|
|
const filesById = new Map(files.map((file) => [file.id, file]));
|
|
return links.flatMap((link) => {
|
|
const file = filesById.get(link.fileId);
|
|
return file
|
|
? [
|
|
{
|
|
messageId: link.entityId,
|
|
fileId: file.id,
|
|
displayName: file.displayName,
|
|
mimeType: file.mimeType,
|
|
sizeBytes: file.sizeBytes,
|
|
linkRole: link.linkRole,
|
|
previewStatus: file.previewStatus,
|
|
scanStatus: file.scanStatus,
|
|
},
|
|
]
|
|
: [];
|
|
});
|
|
}
|
|
|
|
function groupAttachmentIds(rows: readonly PersistedAttachmentRow[]): Map<string, string[]> {
|
|
const grouped = new Map<string, string[]>();
|
|
for (const row of rows) {
|
|
const fileIds = grouped.get(row.messageId) ?? [];
|
|
fileIds.push(row.fileId);
|
|
grouped.set(row.messageId, fileIds);
|
|
}
|
|
return grouped;
|
|
}
|
|
|
|
async function listMessageFeatureRecords(
|
|
tx: DbTransactionClient,
|
|
context: ChatRepositoryContext,
|
|
chatId: string,
|
|
messageIds: readonly string[]
|
|
): Promise<ChatMessageFeatureRecord[]> {
|
|
if (messageIds.length === 0) return [];
|
|
|
|
const [reactions, threads, pins] = await Promise.all([
|
|
tx.teamChatReaction.findMany({
|
|
where: withTenantScope(context.tenantId, {
|
|
messageId: { in: [...messageIds] },
|
|
message: { chatId, chat: memberChannelRelation(context) },
|
|
}),
|
|
orderBy: [{ reactedAt: "asc" }, { id: "asc" }],
|
|
select: { id: true, messageId: true, userId: true, emoji: true, reactedAt: true },
|
|
}),
|
|
tx.teamChatThread.findMany({
|
|
where: withTenantScope(context.tenantId, {
|
|
chatId,
|
|
parentMessageId: { in: [...messageIds] },
|
|
chat: memberChannelRelation(context),
|
|
}),
|
|
orderBy: [{ lastReplyAt: "desc" }, { id: "asc" }],
|
|
select: { id: true, parentMessageId: true, replyCount: true, lastReplyAt: true, participantUserIds: true },
|
|
}),
|
|
tx.teamChatPinnedMessage.findMany({
|
|
where: withTenantScope(context.tenantId, {
|
|
chatId,
|
|
messageId: { in: [...messageIds] },
|
|
chat: memberChannelRelation(context),
|
|
}),
|
|
orderBy: [{ pinnedAt: "desc" }, { id: "asc" }],
|
|
select: { messageId: true, pinnedByUserId: true, pinnedAt: true, note: true },
|
|
}),
|
|
]);
|
|
|
|
return mapPersistedData(() => {
|
|
const byMessageId = new Map<string, ChatMessageFeatureRecord>();
|
|
for (const messageId of messageIds) {
|
|
byMessageId.set(messageId, { messageId, reactions: [], thread: null, pin: null });
|
|
}
|
|
for (const reaction of reactions) {
|
|
const current = byMessageId.get(reaction.messageId);
|
|
if (!current) throw new Error("Reaction escaped the requested message scope");
|
|
byMessageId.set(reaction.messageId, {
|
|
...current,
|
|
reactions: [
|
|
...current.reactions,
|
|
{
|
|
id: normalizeRequiredIdentifier(reaction.id, "reaction id"),
|
|
messageId: reaction.messageId,
|
|
userId: normalizeRequiredIdentifier(reaction.userId, "reaction userId"),
|
|
emoji: reaction.emoji,
|
|
reactedAtIso: reaction.reactedAt.toISOString(),
|
|
},
|
|
],
|
|
});
|
|
}
|
|
for (const thread of threads) {
|
|
const current = byMessageId.get(thread.parentMessageId);
|
|
if (!current) throw new Error("Thread escaped the requested message scope");
|
|
byMessageId.set(thread.parentMessageId, {
|
|
...current,
|
|
thread: {
|
|
id: normalizeRequiredIdentifier(thread.id, "thread id"),
|
|
parentMessageId: thread.parentMessageId,
|
|
replyCount: thread.replyCount,
|
|
lastReplyAtIso: thread.lastReplyAt.toISOString(),
|
|
participantUserIds: [...thread.participantUserIds],
|
|
},
|
|
});
|
|
}
|
|
for (const pin of pins) {
|
|
const current = byMessageId.get(pin.messageId);
|
|
if (!current) throw new Error("Pin escaped the requested message scope");
|
|
byMessageId.set(pin.messageId, {
|
|
...current,
|
|
pin: {
|
|
messageId: pin.messageId,
|
|
pinnedByUserId: normalizeRequiredIdentifier(pin.pinnedByUserId, "pin userId"),
|
|
pinnedAtIso: pin.pinnedAt.toISOString(),
|
|
note: pin.note,
|
|
},
|
|
});
|
|
}
|
|
return [...byMessageId.values()];
|
|
});
|
|
}
|
|
|
|
async function sendTopLevelChatMessageInternal(input: SendTopLevelChatMessageInput): Promise<SendTopLevelChatMessageResult> {
|
|
const normalized = mapPublicInput(() => normalizeSendInput(input));
|
|
|
|
try {
|
|
return await runChatTransaction(input, CHAT_PERMISSIONS.write, async (tx, currentPermissions) => {
|
|
await lockActiveChatMembership(tx, input, normalized.chatId);
|
|
await lockChatEventStream(tx, input.tenantId, normalized.chatId);
|
|
const channel = await requireReadableChannel(tx, input, normalized.chatId);
|
|
const existing = await findIdempotentMessage(tx, input, normalized.clientMessageId);
|
|
const resolvedInput = {
|
|
...normalized,
|
|
mentions: await resolveChatMentionsInBodyWithTx(tx, input, channel, normalized.body, currentPermissions),
|
|
};
|
|
if (existing) {
|
|
return resolveExistingMessageReplay(tx, input, resolvedInput, channel.eventStreamId, existing);
|
|
}
|
|
await lockWritableChatMembership(tx, input, normalized.chatId);
|
|
requireWritableChannelState(channel);
|
|
if (resolvedInput.attachmentFileIds.length > 0) {
|
|
if (!currentPermissions.includes("files.write")) {
|
|
throw new CatalogError(foundationErrors.notFound, { permission: "files.write" });
|
|
}
|
|
if (!(await tenantHasFilesModuleWithPermissionsTx(tx, input.tenantId, currentPermissions))) {
|
|
throw new CatalogError(foundationErrors.notFound, { module: featureKeys.files });
|
|
}
|
|
}
|
|
const attachmentFiles = await requireWritableAttachmentFiles(tx, input, resolvedInput.attachmentFileIds);
|
|
|
|
const message = await tx.teamChatMessage.create({
|
|
data: withTenantScope(input.tenantId, {
|
|
chatId: resolvedInput.chatId,
|
|
authorUserId: input.userId,
|
|
clientMessageId: resolvedInput.clientMessageId,
|
|
body: resolvedInput.body,
|
|
bodyFormat: "markdown",
|
|
parentMessageId: null,
|
|
mentions: resolvedInput.mentions as unknown as Prisma.InputJsonValue,
|
|
linkPreviews: resolvedInput.linkPreviews as unknown as Prisma.InputJsonValue,
|
|
}),
|
|
select: CHAT_MESSAGE_SELECT,
|
|
});
|
|
if (attachmentFiles.length > 0) {
|
|
await tx.fileEntityLink.createMany({
|
|
data: attachmentFiles.map((file) =>
|
|
withTenantScope(input.tenantId, {
|
|
createdByUserId: input.userId,
|
|
fileId: file.id,
|
|
entityType: "chat_message" as const,
|
|
entityId: message.id,
|
|
linkRole: attachmentLinkRole(file.mimeType),
|
|
})
|
|
),
|
|
skipDuplicates: true,
|
|
});
|
|
}
|
|
const realtimeMessage = mapMessage(message, channel.eventStreamId, resolvedInput.attachmentFileIds);
|
|
const updated = await tx.teamChat.updateMany({
|
|
where: withTenantScope(input.tenantId, { id: resolvedInput.chatId, archivedAt: null }),
|
|
data: { lastMessageAt: message.createdAt },
|
|
});
|
|
if (updated.count !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
|
|
}
|
|
|
|
const eventData = { message: realtimeMessage };
|
|
const event = await tx.teamChatEvent.create({
|
|
data: withTenantScope(input.tenantId, {
|
|
chatId: resolvedInput.chatId,
|
|
type: toPersistedChatEventType(CHAT_EVENT_NAMES.messageCreated),
|
|
actorUserId: input.userId,
|
|
entityId: message.id,
|
|
requestId: resolvedInput.requestId,
|
|
data: eventData as unknown as Prisma.InputJsonValue,
|
|
}),
|
|
select: CHAT_EVENT_SELECT,
|
|
});
|
|
const realtimeEvent = mapEvent(event, channel.eventStreamId);
|
|
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event: realtimeEvent });
|
|
await publishChatLinkPreviewRequest(tx as unknown as OutboxPublisherTransaction, {
|
|
tenantId: input.tenantId,
|
|
chatId: resolvedInput.chatId,
|
|
messageId: message.id,
|
|
requestId: resolvedInput.requestId,
|
|
body: resolvedInput.body,
|
|
});
|
|
await publishTopLevelChatMessageEffectsWithTx(tx, input, {
|
|
channel,
|
|
messageId: message.id,
|
|
requestId: resolvedInput.requestId,
|
|
body: resolvedInput.body,
|
|
mentions: resolvedInput.mentions,
|
|
});
|
|
await notifyChatMessageRecipients(tx, input, channel, resolvedInput.chatId, realtimeMessage);
|
|
|
|
return {
|
|
message: realtimeMessage,
|
|
event: realtimeEvent,
|
|
replayed: false,
|
|
};
|
|
});
|
|
} catch (error) {
|
|
if (!isMessageIdempotencyUniqueError(error)) {
|
|
throw error;
|
|
}
|
|
|
|
const replay = await runChatTransaction(input, CHAT_PERMISSIONS.write, async (tx, currentPermissions) => {
|
|
await lockActiveChatMembership(tx, input, normalized.chatId);
|
|
const channel = await requireReadableChannel(tx, input, normalized.chatId);
|
|
const resolvedInput = {
|
|
...normalized,
|
|
mentions: await resolveChatMentionsInBodyWithTx(tx, input, channel, normalized.body, currentPermissions),
|
|
};
|
|
const existing = await findIdempotentMessage(tx, input, resolvedInput.clientMessageId);
|
|
if (!existing) return null;
|
|
return resolveExistingMessageReplay(tx, input, resolvedInput, channel.eventStreamId, existing);
|
|
});
|
|
|
|
if (!replay) throw error;
|
|
return replay;
|
|
}
|
|
}
|
|
|
|
async function getChatMessageTaskSourceInternal(input: GetChatMessageTaskSourceInput): Promise<ChatMessageTaskSourceRecord> {
|
|
return withWritableChatMessageTaskSourceInternal(input, async (_tx, source) => source);
|
|
}
|
|
|
|
async function withWritableChatMessageTaskSourceInternal<TResult>(
|
|
input: WithWritableChatMessageTaskSourceInput,
|
|
operation: (tx: DbTransactionClient, source: ChatMessageTaskSourceRecord, currentPermissions: readonly string[]) => Promise<TResult>
|
|
): Promise<TResult> {
|
|
const { chatId, messageId } = mapPublicInput(() => ({
|
|
chatId: normalizeRequiredIdentifier(input.chatId, "chatId"),
|
|
messageId: normalizeRequiredIdentifier(input.messageId, "messageId"),
|
|
}));
|
|
return runChatTransaction(input, CHAT_PERMISSIONS.write, async (tx, currentPermissions) => {
|
|
await lockWritableChatMembership(tx, input, chatId);
|
|
const channel = await requireReadableChannel(tx, input, chatId);
|
|
requireWritableChannelState(channel);
|
|
const message = await tx.teamChatMessage.findFirst({
|
|
where: withTenantScope(input.tenantId, {
|
|
id: messageId,
|
|
chatId,
|
|
bodyFormat: "markdown" as const,
|
|
deletedAt: null,
|
|
chat: memberChannelRelation(input),
|
|
}),
|
|
select: { id: true, body: true },
|
|
});
|
|
if (!message) throw new CatalogError(foundationErrors.notFound, { chat: "message-not-visible" });
|
|
return operation(tx, { chatId, messageId: message.id, body: message.body, projectId: channel.projektId }, currentPermissions);
|
|
});
|
|
}
|
|
|
|
async function fillChatEventGapInternal(input: FillChatEventGapInput): Promise<ChatEventGapResult> {
|
|
const { chatId, afterCursor, parsedCursor, limit } = mapPublicInput(() => {
|
|
const normalizedCursor = normalizeChatResumeCursor(input.afterCursor);
|
|
return {
|
|
chatId: normalizeRequiredIdentifier(input.chatId, "chatId"),
|
|
afterCursor: normalizedCursor,
|
|
parsedCursor: parseChatResumeCursor(normalizedCursor),
|
|
limit: normalizeLimit(input.limit, DEFAULT_EVENT_GAP_LIMIT, MAX_EVENT_GAP_LIMIT, "event gap limit"),
|
|
};
|
|
});
|
|
|
|
return runChatTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
|
|
await lockActiveChatMembership(tx, input, chatId);
|
|
const channel = await requireReadableChannel(tx, input, chatId);
|
|
if (parsedCursor.streamId !== null && parsedCursor.streamId !== channel.eventStreamId) {
|
|
return { status: "reset_required", currentStreamId: channel.eventStreamId };
|
|
}
|
|
|
|
const rows = await tx.teamChatEvent.findMany({
|
|
where: withTenantScope(input.tenantId, {
|
|
chatId,
|
|
sequence: { gt: BigInt(parsedCursor.sequence) },
|
|
chat: memberChannelRelation(input),
|
|
}),
|
|
orderBy: { sequence: "asc" },
|
|
take: limit + 1,
|
|
select: CHAT_EVENT_SELECT,
|
|
});
|
|
const hasMore = rows.length > limit;
|
|
const events = rows.slice(0, limit).map((row) => mapEvent(row, channel.eventStreamId));
|
|
|
|
return {
|
|
status: "ok",
|
|
events,
|
|
nextCursor: events.at(-1)?.cursor ?? afterCursor,
|
|
hasMore,
|
|
};
|
|
});
|
|
}
|
|
|
|
async function markChatMessageReadInternal(input: MarkChatMessageReadInput): Promise<MarkChatMessageReadResult> {
|
|
const normalized = mapPublicInput(() => ({
|
|
chatId: normalizeRequiredIdentifier(input.chatId, "chatId"),
|
|
messageId: normalizeRequiredIdentifier(input.messageId, "messageId"),
|
|
requestId: normalizeRequiredIdentifier(input.requestId, "requestId"),
|
|
}));
|
|
|
|
return runChatTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
|
|
await lockActiveChatMembership(tx, input, normalized.chatId);
|
|
await lockChatEventStream(tx, input.tenantId, normalized.chatId);
|
|
const channel = await requireReadableChannel(tx, input, normalized.chatId);
|
|
const existingEvent = await tx.teamChatEvent.findFirst({
|
|
where: withTenantScope(input.tenantId, {
|
|
chatId: normalized.chatId,
|
|
type: toPersistedChatEventType(CHAT_EVENT_NAMES.readReceipt),
|
|
actorUserId: input.userId,
|
|
entityId: normalized.messageId,
|
|
chat: memberChannelRelation(input),
|
|
}),
|
|
orderBy: { sequence: "asc" },
|
|
select: CHAT_EVENT_SELECT,
|
|
});
|
|
if (existingEvent) {
|
|
return { event: mapEvent(existingEvent, channel.eventStreamId), replayed: true };
|
|
}
|
|
|
|
const message = await tx.teamChatMessage.findFirst({
|
|
where: withTenantScope(input.tenantId, {
|
|
id: normalized.messageId,
|
|
chatId: normalized.chatId,
|
|
chat: memberChannelRelation(input),
|
|
}),
|
|
select: { id: true, createdAt: true, parentMessageId: true },
|
|
});
|
|
if (!message) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "message-not-visible" });
|
|
}
|
|
|
|
const read = await tx.teamChatRead.upsert({
|
|
where: { messageId_userId: { messageId: message.id, userId: input.userId } },
|
|
create: withTenantScope(input.tenantId, { messageId: message.id, userId: input.userId }),
|
|
update: { readAt: new Date() },
|
|
select: { readAt: true },
|
|
});
|
|
// Thread receipts are exact per-message markers but must never advance the
|
|
// top-level channel unread cursor.
|
|
if (message.parentMessageId === null) {
|
|
const membership = await tx.teamChatMember.findUnique({
|
|
where: { chatId_userId: { chatId: normalized.chatId, userId: input.userId } },
|
|
select: { lastReadMessage: { select: { id: true, createdAt: true } } },
|
|
});
|
|
if (!membership) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
|
}
|
|
const currentReadMessage = membership.lastReadMessage;
|
|
const advancesReadCursor =
|
|
!currentReadMessage ||
|
|
currentReadMessage.createdAt < message.createdAt ||
|
|
(currentReadMessage.createdAt.getTime() === message.createdAt.getTime() && currentReadMessage.id < message.id);
|
|
if (advancesReadCursor) {
|
|
const updated = await tx.teamChatMember.updateMany({
|
|
where: withTenantScope(input.tenantId, {
|
|
chatId: normalized.chatId,
|
|
userId: input.userId,
|
|
leftAt: null,
|
|
}),
|
|
data: { lastReadMessageId: message.id, lastReadAt: read.readAt },
|
|
});
|
|
if (updated.count !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
|
}
|
|
}
|
|
}
|
|
|
|
const event = await tx.teamChatEvent.create({
|
|
data: withTenantScope(input.tenantId, {
|
|
chatId: normalized.chatId,
|
|
type: toPersistedChatEventType(CHAT_EVENT_NAMES.readReceipt),
|
|
actorUserId: input.userId,
|
|
entityId: message.id,
|
|
requestId: normalized.requestId,
|
|
data: {
|
|
messageId: message.id,
|
|
userId: input.userId,
|
|
readAt: read.readAt.toISOString(),
|
|
} as Prisma.InputJsonValue,
|
|
}),
|
|
select: CHAT_EVENT_SELECT,
|
|
});
|
|
return { event: mapEvent(event, channel.eventStreamId), replayed: false };
|
|
});
|
|
}
|
|
|
|
async function authorizeChatGatewayConnectionInternal(input: Extract<ChatRepositoryContext, { sessionId: string }>): Promise<void> {
|
|
await runChatTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async () => undefined);
|
|
}
|
|
|
|
async function assertMemberChannelAccessInternal(input: Extract<ChatRepositoryContext, { sessionId: string }> & { readonly chatId: string }): Promise<void> {
|
|
const chatId = mapPublicInput(() => normalizeRequiredIdentifier(input.chatId, "chatId"));
|
|
await runChatTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
|
|
await lockActiveChatMembership(tx, input, chatId);
|
|
await requireReadableChannel(tx, input, chatId);
|
|
});
|
|
}
|
|
|
|
async function assertMemberChannelWriteAccessInternal(
|
|
input: Extract<ChatRepositoryContext, { sessionId: string }> & { readonly chatId: string }
|
|
): Promise<void> {
|
|
const chatId = mapPublicInput(() => normalizeRequiredIdentifier(input.chatId, "chatId"));
|
|
await runChatTransaction(input, CHAT_PERMISSIONS.write, async (tx) => {
|
|
await lockWritableChatMembership(tx, input, chatId);
|
|
requireWritableChannelState(await requireReadableChannel(tx, input, chatId));
|
|
});
|
|
}
|
|
|
|
async function revalidateChatGatewayAccessInternal(input: RevalidateChatGatewayAccessInput): Promise<void> {
|
|
const chatIds = mapPublicInput(() => {
|
|
if (!Array.isArray(input.chatIds) || input.chatIds.length > MAX_GATEWAY_REVALIDATION_CHAT_IDS) {
|
|
throw new CatalogError(chatErrors.invalidInput);
|
|
}
|
|
return [...new Set(input.chatIds.map((chatId) => normalizeRequiredIdentifier(chatId, "chatId")))].sort();
|
|
});
|
|
|
|
await runChatTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
|
|
if (chatIds.length === 0) return;
|
|
const activeChatIds = new Set(await lockActiveChatMemberships(tx, input));
|
|
if (chatIds.some((chatId) => !activeChatIds.has(chatId))) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
|
}
|
|
});
|
|
}
|
|
|
|
export const listMemberChannels = listMemberChannelsInternal;
|
|
export const getMemberChannelDetail = getMemberChannelDetailInternal;
|
|
export const sendTopLevelChatMessage = sendTopLevelChatMessageInternal;
|
|
export const getChatMessageTaskSource = getChatMessageTaskSourceInternal;
|
|
export const withWritableChatMessageTaskSource = withWritableChatMessageTaskSourceInternal;
|
|
export const fillChatEventGap = fillChatEventGapInternal;
|
|
export const markChatMessageRead = markChatMessageReadInternal;
|
|
export const authorizeChatGatewayConnection = authorizeChatGatewayConnectionInternal;
|
|
export const assertMemberChannelAccess = assertMemberChannelAccessInternal;
|
|
export const assertMemberChannelWriteAccess = assertMemberChannelWriteAccessInternal;
|
|
export const revalidateChatGatewayAccess = revalidateChatGatewayAccessInternal;
|
|
/** Shared server boundary for chat repositories that need the same RLS,
|
|
* tenant-membership, module and atomic-permission enforcement. */
|
|
export const runChatRepositoryTransaction = runChatTransaction;
|
|
|
|
function runChatTransaction<TResult>(
|
|
context: ChatRepositoryContext,
|
|
permission: string,
|
|
operation: (tx: DbTransactionClient, currentPermissions: readonly string[]) => Promise<TResult>
|
|
): Promise<TResult> {
|
|
return runWithRlsContext({ tenantId: context.tenantId, userId: context.userId }, () =>
|
|
getWriteDbClient().$transaction(async (tx) => {
|
|
const permissions = await resolveCurrentPermissions(tx, context);
|
|
await requireActiveTenantMembership(tx, context);
|
|
await requireCurrentChatModuleAccess(tx, context, permissions);
|
|
const permissionContext = { tenantId: context.tenantId, userId: context.userId, permissions };
|
|
return withPermission(
|
|
permission,
|
|
() => permissionContext,
|
|
() => operation(tx, permissions)
|
|
)();
|
|
})
|
|
);
|
|
}
|
|
|
|
async function resolveCurrentPermissions(tx: DbTransactionClient, context: ChatRepositoryContext): Promise<readonly string[]> {
|
|
if ("sessionId" in context) {
|
|
const rawSessionId = context.sessionId;
|
|
const sessionId = mapPublicInput(() => {
|
|
if (typeof rawSessionId !== "string") throw new Error("sessionId is required for gateway repository access");
|
|
return normalizeRequiredIdentifier(rawSessionId, "sessionId");
|
|
});
|
|
await requireActiveGatewaySession(tx, context, sessionId);
|
|
}
|
|
|
|
return lockCurrentTenantPermissions(tx, context);
|
|
}
|
|
|
|
async function requireActiveGatewaySession(
|
|
tx: DbTransactionClient,
|
|
context: Pick<ChatRepositoryContext, "tenantId" | "userId">,
|
|
sessionId: string
|
|
): Promise<void> {
|
|
const rows = await tx.$queryRaw<Array<{ id: string }>>`
|
|
SELECT session_row."id"
|
|
FROM "UserSession" AS session_row
|
|
INNER JOIN "User" AS user_row ON user_row."id" = session_row."userId"
|
|
WHERE session_row."id" = ${sessionId}
|
|
AND session_row."userId" = ${context.userId}
|
|
AND session_row."revokedAt" IS NULL
|
|
AND session_row."expiresAt" > CURRENT_TIMESTAMP
|
|
AND user_row."active" = TRUE
|
|
AND user_row."pendingDeletion" = FALSE
|
|
AND user_row."pseudonymized" = FALSE
|
|
FOR SHARE OF session_row, user_row
|
|
`;
|
|
if (rows.length !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound);
|
|
}
|
|
}
|
|
|
|
async function lockCurrentTenantPermissions(tx: DbTransactionClient, context: Pick<ChatRepositoryContext, "tenantId" | "userId">): Promise<readonly string[]> {
|
|
const rows = await tx.$queryRaw<Array<{ name: string }>>`
|
|
SELECT permission_row."name"
|
|
FROM "UserRole" AS user_role
|
|
INNER JOIN "Role" AS role_row ON role_row."id" = user_role."roleId"
|
|
INNER JOIN "RolePermission" AS role_permission ON role_permission."roleId" = role_row."id"
|
|
INNER JOIN "Permission" AS permission_row ON permission_row."id" = role_permission."permissionId"
|
|
WHERE user_role."tenantId" = ${context.tenantId}
|
|
AND user_role."userId" = ${context.userId}
|
|
AND role_row."type" = 'app'
|
|
AND (role_row."tenantId" IS NULL OR role_row."tenantId" = ${context.tenantId})
|
|
ORDER BY permission_row."name" ASC
|
|
FOR SHARE OF user_role
|
|
`;
|
|
return [...new Set(rows.map((row) => row.name))];
|
|
}
|
|
|
|
async function requireCurrentChatModuleAccess(
|
|
tx: DbTransactionClient,
|
|
context: Pick<ChatRepositoryContext, "tenantId">,
|
|
permissions: readonly string[]
|
|
): Promise<void> {
|
|
if (!(await tenantHasChatModuleWithPermissionsTx(tx, context.tenantId, permissions))) {
|
|
throw new CatalogError(foundationErrors.notFound, { module: featureKeys.chat });
|
|
}
|
|
}
|
|
|
|
async function requireActiveTenantMembership(tx: DbTransactionClient, context: ChatRepositoryContext): Promise<void> {
|
|
const rows = await tx.$queryRaw<Array<{ id: string }>>`
|
|
SELECT tu."id"
|
|
FROM "TenantUser" AS tu
|
|
INNER JOIN "User" AS u ON u."id" = tu."userId"
|
|
INNER JOIN "Tenant" AS t ON t."id" = tu."tenantId"
|
|
WHERE tu."tenantId" = ${context.tenantId}
|
|
AND tu."userId" = ${context.userId}
|
|
AND tu."status" = ${ACTIVE_TENANT_USER_STATUS}
|
|
AND u."active" = TRUE
|
|
AND t."active" = TRUE
|
|
FOR SHARE OF tu, u, t
|
|
`;
|
|
if (rows.length !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound);
|
|
}
|
|
}
|
|
|
|
type LockedChatMembershipRow = { id: string; chatId: string };
|
|
|
|
async function lockActiveChatMemberships(tx: DbTransactionClient, context: ChatRepositoryContext): Promise<string[]> {
|
|
const rows = await tx.$queryRaw<LockedChatMembershipRow[]>`
|
|
SELECT "id", "chatId"
|
|
FROM "TeamChatMember"
|
|
WHERE "tenantId" = ${context.tenantId}
|
|
AND "userId" = ${context.userId}
|
|
AND "leftAt" IS NULL
|
|
ORDER BY "chatId" ASC
|
|
FOR SHARE
|
|
`;
|
|
return rows.map((row) => row.chatId);
|
|
}
|
|
|
|
async function lockActiveChatMembership(tx: DbTransactionClient, context: ChatRepositoryContext, chatId: string): Promise<void> {
|
|
const rows = await tx.$queryRaw<LockedChatMembershipRow[]>`
|
|
SELECT "id", "chatId"
|
|
FROM "TeamChatMember"
|
|
WHERE "tenantId" = ${context.tenantId}
|
|
AND "userId" = ${context.userId}
|
|
AND "chatId" = ${chatId}
|
|
AND "leftAt" IS NULL
|
|
FOR SHARE
|
|
`;
|
|
if (rows.length !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
|
}
|
|
}
|
|
|
|
async function lockWritableChatMembership(tx: DbTransactionClient, context: ChatRepositoryContext, chatId: string): Promise<void> {
|
|
const rows = await tx.$queryRaw<LockedChatMembershipRow[]>`
|
|
SELECT "id", "chatId"
|
|
FROM "TeamChatMember"
|
|
WHERE "tenantId" = ${context.tenantId}
|
|
AND "userId" = ${context.userId}
|
|
AND "chatId" = ${chatId}
|
|
AND "leftAt" IS NULL
|
|
AND "writeRevokedAt" IS NULL
|
|
FOR SHARE
|
|
`;
|
|
if (rows.length !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
|
|
}
|
|
}
|
|
|
|
function memberChannelRelation(context: ChatRepositoryContext) {
|
|
return withTenantScope(context.tenantId, {
|
|
members: {
|
|
some: withTenantScope(context.tenantId, { userId: context.userId, leftAt: null }),
|
|
},
|
|
});
|
|
}
|
|
|
|
async function listMemberChannelCandidates(
|
|
tx: DbTransactionClient,
|
|
context: ChatRepositoryContext,
|
|
input: NormalizedMemberChannelListInput
|
|
): Promise<MemberChannelCandidateRow[]> {
|
|
const searchPattern = `%${escapeLikePattern(input.query)}%`;
|
|
const cursor = input.afterCursor;
|
|
const hasCursor = cursor !== null;
|
|
const cursorIsPinned = cursor?.isPinned ?? false;
|
|
const cursorHasLastMessageAt = cursor?.lastMessageAt !== null && cursor?.lastMessageAt !== undefined;
|
|
const cursorLastMessageAt = cursor?.lastMessageAt ?? new Date(0);
|
|
const cursorCreatedAt = cursor?.createdAt ?? new Date(0);
|
|
const cursorChatId = cursor?.chatId ?? "cursor-placeholder";
|
|
|
|
const rows = await tx.$queryRaw<MemberChannelCandidateRow[]>`
|
|
WITH list_candidates AS MATERIALIZED (
|
|
SELECT list_channel."id" AS "chatId",
|
|
list_channel."tenantId" AS "tenantId",
|
|
list_channel."eventStreamId" AS "eventStreamId",
|
|
list_viewer."isPinned" AS "isPinned",
|
|
list_viewer."lastReadMessageId" AS "lastReadMessageId",
|
|
list_channel."lastMessageAt" AS "lastMessageAt",
|
|
list_channel."createdAt" AS "createdAt"
|
|
FROM "TeamChatMember" AS list_viewer
|
|
INNER JOIN "TeamChat" AS list_channel
|
|
ON list_channel."tenantId" = list_viewer."tenantId"
|
|
AND list_channel."id" = list_viewer."chatId"
|
|
LEFT JOIN "TeamChatMessage" AS list_cursor
|
|
ON list_cursor."tenantId" = list_viewer."tenantId"
|
|
AND list_cursor."chatId" = list_viewer."chatId"
|
|
AND list_cursor."id" = list_viewer."lastReadMessageId"
|
|
AND list_cursor."parentMessageId" IS NULL
|
|
WHERE list_viewer."tenantId" = ${context.tenantId}
|
|
AND list_viewer."userId" = ${context.userId}
|
|
AND list_viewer."leftAt" IS NULL
|
|
AND (${input.includeArchived}::boolean = TRUE OR list_channel."archivedAt" IS NULL)
|
|
AND (${input.view}::text <> 'pinned' OR list_viewer."isPinned" = TRUE)
|
|
AND (${input.view}::text <> 'projects' OR list_channel."kind"::text = 'project')
|
|
AND (${input.view}::text <> 'groups' OR list_channel."kind"::text = 'group')
|
|
AND (${input.view}::text <> 'direct' OR list_channel."kind"::text = 'dm')
|
|
AND (
|
|
${input.view}::text NOT IN ('unread', 'mentions')
|
|
OR EXISTS (
|
|
SELECT 1
|
|
FROM "TeamChatMessage" AS list_unread_message
|
|
WHERE list_unread_message."tenantId" = list_viewer."tenantId"
|
|
AND list_unread_message."chatId" = list_viewer."chatId"
|
|
AND list_unread_message."parentMessageId" IS NULL
|
|
AND list_unread_message."deletedAt" IS NULL
|
|
AND (list_unread_message."authorUserId" IS NULL OR list_unread_message."authorUserId" <> ${context.userId})
|
|
AND (
|
|
list_viewer."lastReadMessageId" IS NULL
|
|
OR list_cursor."id" IS NULL
|
|
OR (list_unread_message."createdAt", list_unread_message."id") > (list_cursor."createdAt", list_cursor."id")
|
|
)
|
|
AND (
|
|
${input.view}::text <> 'mentions'
|
|
OR list_unread_message."mentions" @> jsonb_build_array(
|
|
jsonb_build_object('type', 'user', 'id', ${context.userId}::text)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
AND (
|
|
${input.query}::text = ''
|
|
OR COALESCE(list_channel."name", '') ILIKE ${searchPattern} ESCAPE '!'
|
|
OR COALESCE(list_channel."description", '') ILIKE ${searchPattern} ESCAPE '!'
|
|
OR EXISTS (
|
|
SELECT 1
|
|
FROM "TeamChatMember" AS search_member
|
|
INNER JOIN "TenantUser" AS search_tenant_user
|
|
ON search_tenant_user."tenantId" = search_member."tenantId"
|
|
AND search_tenant_user."userId" = search_member."userId"
|
|
AND search_tenant_user."status" = ${ACTIVE_TENANT_USER_STATUS}
|
|
INNER JOIN "User" AS search_user
|
|
ON search_user."id" = search_member."userId"
|
|
AND search_user."active" = TRUE
|
|
AND search_user."pendingDeletion" = FALSE
|
|
WHERE search_member."tenantId" = list_viewer."tenantId"
|
|
AND search_member."chatId" = list_viewer."chatId"
|
|
AND search_member."userId" <> ${context.userId}
|
|
AND search_member."leftAt" IS NULL
|
|
AND (
|
|
NULLIF(TRIM(CONCAT_WS(' ', search_user."firstName", search_user."lastName")), '') ILIKE ${searchPattern} ESCAPE '!'
|
|
OR search_user."email" ILIKE ${searchPattern} ESCAPE '!'
|
|
)
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1
|
|
FROM "TeamChatMessage" AS search_message
|
|
WHERE search_message."tenantId" = list_viewer."tenantId"
|
|
AND search_message."chatId" = list_viewer."chatId"
|
|
AND search_message."parentMessageId" IS NULL
|
|
AND search_message."deletedAt" IS NULL
|
|
AND search_message."body" ILIKE ${searchPattern} ESCAPE '!'
|
|
)
|
|
)
|
|
AND (
|
|
${hasCursor}::boolean = FALSE
|
|
OR (${cursorIsPinned}::boolean = TRUE AND list_viewer."isPinned" = FALSE)
|
|
OR (
|
|
list_viewer."isPinned" = ${cursorIsPinned}::boolean
|
|
AND (
|
|
(
|
|
${cursorHasLastMessageAt}::boolean = TRUE
|
|
AND (
|
|
list_channel."lastMessageAt" < ${cursorLastMessageAt}::timestamp(3)
|
|
OR list_channel."lastMessageAt" IS NULL
|
|
OR (
|
|
list_channel."lastMessageAt" = ${cursorLastMessageAt}::timestamp(3)
|
|
AND (
|
|
list_channel."createdAt" < ${cursorCreatedAt}::timestamp(3)
|
|
OR (list_channel."createdAt" = ${cursorCreatedAt}::timestamp(3) AND list_channel."id" < ${cursorChatId})
|
|
)
|
|
)
|
|
)
|
|
)
|
|
OR (
|
|
${cursorHasLastMessageAt}::boolean = FALSE
|
|
AND list_channel."lastMessageAt" IS NULL
|
|
AND (
|
|
list_channel."createdAt" < ${cursorCreatedAt}::timestamp(3)
|
|
OR (list_channel."createdAt" = ${cursorCreatedAt}::timestamp(3) AND list_channel."id" < ${cursorChatId})
|
|
)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
ORDER BY list_viewer."isPinned" DESC,
|
|
list_channel."lastMessageAt" DESC NULLS LAST,
|
|
list_channel."createdAt" DESC,
|
|
list_channel."id" DESC
|
|
LIMIT ${input.limit + 1}
|
|
FOR SHARE OF list_viewer
|
|
)
|
|
SELECT list_candidate."chatId" AS "chatId",
|
|
list_candidate."isPinned" AS "isPinned",
|
|
list_candidate."lastMessageAt" AS "lastMessageAt",
|
|
list_candidate."createdAt" AS "createdAt",
|
|
list_candidate."eventStreamId" AS "eventStreamId",
|
|
list_latest_event."sequence" AS "latestEventSequence",
|
|
list_unread."unreadCount" AS "unreadCount",
|
|
list_unread."hasUnreadMention" AS "hasUnreadMention"
|
|
FROM list_candidates AS list_candidate
|
|
CROSS JOIN LATERAL (
|
|
SELECT COUNT(*)::integer AS "unreadCount",
|
|
COALESCE(
|
|
BOOL_OR(
|
|
unread_message."mentions" @> jsonb_build_array(
|
|
jsonb_build_object('type', 'user', 'id', ${context.userId}::text)
|
|
)
|
|
),
|
|
FALSE
|
|
) AS "hasUnreadMention"
|
|
FROM "TeamChatMessage" AS unread_message
|
|
LEFT JOIN "TeamChatMessage" AS unread_cursor
|
|
ON unread_cursor."tenantId" = list_candidate."tenantId"
|
|
AND unread_cursor."chatId" = list_candidate."chatId"
|
|
AND unread_cursor."id" = list_candidate."lastReadMessageId"
|
|
AND unread_cursor."parentMessageId" IS NULL
|
|
WHERE unread_message."tenantId" = list_candidate."tenantId"
|
|
AND unread_message."chatId" = list_candidate."chatId"
|
|
AND unread_message."parentMessageId" IS NULL
|
|
AND unread_message."deletedAt" IS NULL
|
|
AND (unread_message."authorUserId" IS NULL OR unread_message."authorUserId" <> ${context.userId})
|
|
AND (
|
|
list_candidate."lastReadMessageId" IS NULL
|
|
OR unread_cursor."id" IS NULL
|
|
OR (unread_message."createdAt", unread_message."id") > (unread_cursor."createdAt", unread_cursor."id")
|
|
)
|
|
) AS list_unread
|
|
LEFT JOIN LATERAL (
|
|
SELECT list_event."sequence" AS "sequence"
|
|
FROM "TeamChatEvent" AS list_event
|
|
WHERE list_event."tenantId" = list_candidate."tenantId"
|
|
AND list_event."chatId" = list_candidate."chatId"
|
|
ORDER BY list_event."sequence" DESC
|
|
LIMIT 1
|
|
) AS list_latest_event ON TRUE
|
|
ORDER BY list_candidate."isPinned" DESC,
|
|
list_candidate."lastMessageAt" DESC NULLS LAST,
|
|
list_candidate."createdAt" DESC,
|
|
list_candidate."chatId" DESC
|
|
`;
|
|
|
|
return mapPersistedData(() => {
|
|
const seenChatIds = new Set<string>();
|
|
return rows.map((row) => {
|
|
const chatId = normalizeRequiredIdentifier(row.chatId, "channel candidate chatId");
|
|
if (
|
|
seenChatIds.has(chatId) ||
|
|
typeof row.isPinned !== "boolean" ||
|
|
typeof row.eventStreamId !== "string" ||
|
|
!row.eventStreamId.trim() ||
|
|
(row.latestEventSequence !== null && (typeof row.latestEventSequence !== "bigint" || row.latestEventSequence < 1n)) ||
|
|
!Number.isInteger(row.unreadCount) ||
|
|
row.unreadCount < 0 ||
|
|
typeof row.hasUnreadMention !== "boolean" ||
|
|
!(row.createdAt instanceof Date) ||
|
|
!Number.isFinite(row.createdAt.getTime()) ||
|
|
(row.lastMessageAt !== null && (!(row.lastMessageAt instanceof Date) || !Number.isFinite(row.lastMessageAt.getTime())))
|
|
) {
|
|
throw new Error("Invalid channel candidate projection");
|
|
}
|
|
seenChatIds.add(chatId);
|
|
return {
|
|
chatId,
|
|
isPinned: row.isPinned,
|
|
lastMessageAt: row.lastMessageAt,
|
|
createdAt: row.createdAt,
|
|
eventStreamId: row.eventStreamId,
|
|
latestEventSequence: row.latestEventSequence,
|
|
unreadCount: row.unreadCount,
|
|
hasUnreadMention: row.hasUnreadMention,
|
|
};
|
|
});
|
|
});
|
|
}
|
|
|
|
async function requireReadableChannel(tx: DbTransactionClient, context: ChatRepositoryContext, chatId: string): Promise<PersistedMemberChannelRow> {
|
|
const memberScope = withTenantScope(context.tenantId, { userId: context.userId, leftAt: null });
|
|
const channel = await tx.teamChat.findFirst({
|
|
where: withTenantScope(context.tenantId, { id: chatId, members: { some: memberScope } }),
|
|
select: {
|
|
id: true,
|
|
kind: true,
|
|
name: true,
|
|
description: true,
|
|
projektId: true,
|
|
isPrivate: true,
|
|
archivedAt: true,
|
|
lastMessageAt: true,
|
|
eventStreamId: true,
|
|
members: {
|
|
where: memberScope,
|
|
take: 1,
|
|
select: {
|
|
roleInChat: true,
|
|
notificationPref: true,
|
|
lastReadMessageId: true,
|
|
lastReadAt: true,
|
|
isPinned: true,
|
|
writeRevokedAt: true,
|
|
},
|
|
},
|
|
_count: { select: { members: { where: withTenantScope(context.tenantId, { leftAt: null }) } } },
|
|
messages: {
|
|
where: withTenantScope(context.tenantId, {
|
|
parentMessageId: null,
|
|
chat: memberChannelRelation(context),
|
|
}),
|
|
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
|
take: 1,
|
|
select: CHAT_MESSAGE_SELECT,
|
|
},
|
|
},
|
|
});
|
|
if (!channel || channel.members.length !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
|
}
|
|
return channel;
|
|
}
|
|
|
|
async function listParticipantProfiles(
|
|
tx: DbTransactionClient,
|
|
context: ChatRepositoryContext,
|
|
chatIds: readonly string[]
|
|
): Promise<ParticipantProfileProjectionRow[]> {
|
|
if (chatIds.length === 0) return [];
|
|
|
|
return tx.$queryRaw<ParticipantProfileProjectionRow[]>`
|
|
SELECT participant."chatId" AS "chatId",
|
|
participant."userId" AS "userId",
|
|
COALESCE(
|
|
NULLIF(TRIM(CONCAT_WS(' ', participant_user."firstName", participant_user."lastName")), ''),
|
|
participant_user."email"
|
|
) AS "displayName",
|
|
participant_user."avatar" AS "avatarUrl"
|
|
FROM "TeamChatMember" AS participant
|
|
INNER JOIN "TenantUser" AS participant_tenant_user
|
|
ON participant_tenant_user."tenantId" = participant."tenantId"
|
|
AND participant_tenant_user."userId" = participant."userId"
|
|
AND participant_tenant_user."status" = ${ACTIVE_TENANT_USER_STATUS}
|
|
INNER JOIN "User" AS participant_user
|
|
ON participant_user."id" = participant."userId"
|
|
AND participant_user."active" = TRUE
|
|
AND participant_user."pendingDeletion" = FALSE
|
|
WHERE participant."tenantId" = ${context.tenantId}
|
|
AND participant."chatId" = ANY(${chatIds}::text[])
|
|
AND participant."leftAt" IS NULL
|
|
ORDER BY participant."chatId" ASC, "displayName" ASC, participant."userId" ASC
|
|
`;
|
|
}
|
|
|
|
async function listChannelListParticipantProfiles(
|
|
tx: DbTransactionClient,
|
|
context: ChatRepositoryContext,
|
|
channels: readonly PersistedMemberChannelRow[]
|
|
): Promise<ParticipantProfileProjectionRow[]> {
|
|
if (channels.length === 0) return [];
|
|
const chatIds = channels.map((channel) => channel.id);
|
|
const dmChatIds = channels.filter((channel) => channel.kind === "dm").map((channel) => channel.id);
|
|
const lastMessageAuthors = channels.flatMap((channel) => {
|
|
const message = channel.messages?.[0];
|
|
return message?.authorUserId ? [{ chatId: channel.id, userId: message.authorUserId }] : [];
|
|
});
|
|
|
|
return tx.$queryRaw<ParticipantProfileProjectionRow[]>`
|
|
WITH requested_list_participant AS (
|
|
SELECT requested."chatId", requested."userId"
|
|
FROM jsonb_to_recordset(${JSON.stringify(lastMessageAuthors)}::jsonb)
|
|
AS requested("chatId" text, "userId" text)
|
|
)
|
|
SELECT list_participant."chatId" AS "chatId",
|
|
list_participant."userId" AS "userId",
|
|
COALESCE(
|
|
NULLIF(TRIM(CONCAT_WS(' ', list_participant_user."firstName", list_participant_user."lastName")), ''),
|
|
list_participant_user."email"
|
|
) AS "displayName",
|
|
list_participant_user."avatar" AS "avatarUrl"
|
|
FROM "TeamChatMember" AS list_participant
|
|
INNER JOIN "TenantUser" AS list_participant_tenant_user
|
|
ON list_participant_tenant_user."tenantId" = list_participant."tenantId"
|
|
AND list_participant_tenant_user."userId" = list_participant."userId"
|
|
AND list_participant_tenant_user."status" = ${ACTIVE_TENANT_USER_STATUS}
|
|
INNER JOIN "User" AS list_participant_user
|
|
ON list_participant_user."id" = list_participant."userId"
|
|
AND list_participant_user."active" = TRUE
|
|
AND list_participant_user."pendingDeletion" = FALSE
|
|
WHERE list_participant."tenantId" = ${context.tenantId}
|
|
AND list_participant."chatId" = ANY(${chatIds}::text[])
|
|
AND list_participant."leftAt" IS NULL
|
|
AND (
|
|
list_participant."chatId" = ANY(${dmChatIds}::text[])
|
|
OR EXISTS (
|
|
SELECT 1
|
|
FROM requested_list_participant
|
|
WHERE requested_list_participant."chatId" = list_participant."chatId"
|
|
AND requested_list_participant."userId" = list_participant."userId"
|
|
)
|
|
)
|
|
ORDER BY list_participant."chatId" ASC, "displayName" ASC, list_participant."userId" ASC
|
|
`;
|
|
}
|
|
|
|
async function listUnreadProjections(tx: DbTransactionClient, context: ChatRepositoryContext, chatIds: readonly string[]): Promise<UnreadProjectionRow[]> {
|
|
if (chatIds.length === 0) return [];
|
|
|
|
return tx.$queryRaw<UnreadProjectionRow[]>`
|
|
SELECT unread_message."chatId" AS "chatId",
|
|
COUNT(*)::integer AS "unreadCount",
|
|
COALESCE(
|
|
BOOL_OR(
|
|
unread_message."mentions" @> jsonb_build_array(
|
|
jsonb_build_object('type', 'user', 'id', ${context.userId}::text)
|
|
)
|
|
),
|
|
FALSE
|
|
) AS "hasUnreadMention"
|
|
FROM "TeamChatMessage" AS unread_message
|
|
INNER JOIN "TeamChatMember" AS unread_viewer
|
|
ON unread_viewer."tenantId" = unread_message."tenantId"
|
|
AND unread_viewer."chatId" = unread_message."chatId"
|
|
AND unread_viewer."userId" = ${context.userId}
|
|
AND unread_viewer."leftAt" IS NULL
|
|
LEFT JOIN "TeamChatMessage" AS unread_cursor
|
|
ON unread_cursor."tenantId" = unread_viewer."tenantId"
|
|
AND unread_cursor."chatId" = unread_viewer."chatId"
|
|
AND unread_cursor."id" = unread_viewer."lastReadMessageId"
|
|
AND unread_cursor."parentMessageId" IS NULL
|
|
WHERE unread_message."tenantId" = ${context.tenantId}
|
|
AND unread_message."chatId" = ANY(${chatIds}::text[])
|
|
AND unread_message."parentMessageId" IS NULL
|
|
AND unread_message."deletedAt" IS NULL
|
|
AND (unread_message."authorUserId" IS NULL OR unread_message."authorUserId" <> ${context.userId})
|
|
AND (
|
|
unread_viewer."lastReadMessageId" IS NULL
|
|
OR unread_cursor."id" IS NULL
|
|
OR (unread_message."createdAt", unread_message."id") > (unread_cursor."createdAt", unread_cursor."id")
|
|
)
|
|
GROUP BY unread_message."chatId"
|
|
ORDER BY unread_message."chatId" ASC
|
|
`;
|
|
}
|
|
|
|
function groupParticipantProfiles(rows: readonly ParticipantProfileProjectionRow[]): Map<string, ChatParticipantProfileRecord[]> {
|
|
return mapPersistedData(() => {
|
|
const grouped = new Map<string, ChatParticipantProfileRecord[]>();
|
|
for (const row of rows) {
|
|
const chatId = normalizeRequiredIdentifier(row.chatId, "participant chatId");
|
|
const userId = normalizeRequiredIdentifier(row.userId, "participant userId");
|
|
const displayName = row.displayName.trim();
|
|
if (!displayName || (row.avatarUrl !== null && typeof row.avatarUrl !== "string")) {
|
|
throw new Error("Invalid participant profile projection");
|
|
}
|
|
const profiles = grouped.get(chatId) ?? [];
|
|
profiles.push({ userId, displayName, avatarUrl: row.avatarUrl });
|
|
grouped.set(chatId, profiles);
|
|
}
|
|
return grouped;
|
|
});
|
|
}
|
|
|
|
function mapUnreadProjections(rows: readonly UnreadProjectionRow[]): Map<string, UnreadProjection> {
|
|
return mapPersistedData(() => {
|
|
const projections = new Map<string, UnreadProjection>();
|
|
for (const row of rows) {
|
|
const chatId = normalizeRequiredIdentifier(row.chatId, "unread chatId");
|
|
if (!Number.isInteger(row.unreadCount) || row.unreadCount < 0 || typeof row.hasUnreadMention !== "boolean") {
|
|
throw new Error("Invalid unread projection");
|
|
}
|
|
projections.set(chatId, { unreadCount: row.unreadCount, hasUnreadMention: row.hasUnreadMention });
|
|
}
|
|
return projections;
|
|
});
|
|
}
|
|
|
|
function mapCandidateEventCursor(candidate: MemberChannelCandidateRow, hydratedEventStreamId: string): string {
|
|
return mapPersistedData(() => {
|
|
const candidateStreamId = normalizeRequiredIdentifier(candidate.eventStreamId, "candidate event stream id");
|
|
if (candidateStreamId !== normalizeRequiredIdentifier(hydratedEventStreamId, "hydrated event stream id")) {
|
|
throw new Error("Channel event stream changed during list hydration");
|
|
}
|
|
return candidate.latestEventSequence === null ? "0" : mapPersistedCursor(candidateStreamId, candidate.latestEventSequence);
|
|
});
|
|
}
|
|
|
|
function requireWritableChannelState(channel: PersistedMemberChannelRow): void {
|
|
if (channel.archivedAt !== null) {
|
|
throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
|
|
}
|
|
}
|
|
|
|
async function lockChatEventStream(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<void> {
|
|
const lockKey = `chat-event:${tenantId}:${chatId}`;
|
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_EVENT_LOCK_SALT}))`;
|
|
}
|
|
|
|
async function findIdempotentMessage(tx: DbTransactionClient, context: ChatRepositoryContext, clientMessageId: string): Promise<PersistedMessageRow | null> {
|
|
return tx.teamChatMessage.findUnique({
|
|
where: withTenantScope(context.tenantId, {
|
|
tenantId_authorUserId_clientMessageId: {
|
|
tenantId: context.tenantId,
|
|
authorUserId: context.userId,
|
|
clientMessageId,
|
|
},
|
|
chat: memberChannelRelation(context),
|
|
}),
|
|
select: CHAT_MESSAGE_SELECT,
|
|
});
|
|
}
|
|
|
|
async function requireWritableAttachmentFiles(
|
|
tx: DbTransactionClient,
|
|
context: ChatRepositoryContext,
|
|
fileIds: readonly string[]
|
|
): Promise<Array<{ id: string; mimeType: string }>> {
|
|
if (fileIds.length === 0) return [];
|
|
const rows = await tx.file.findMany({
|
|
where: withTenantScope(context.tenantId, {
|
|
id: { in: [...fileIds] },
|
|
createdByUserId: context.userId,
|
|
archivedAt: null,
|
|
}),
|
|
select: { id: true, mimeType: true, scanStatus: true },
|
|
});
|
|
const byId = new Map(rows.map((row) => [row.id, row]));
|
|
if (rows.length !== fileIds.length || fileIds.some((fileId) => !byId.has(fileId))) {
|
|
throw new CatalogError(foundationErrors.notFound, { attachment: "unavailable" });
|
|
}
|
|
if (rows.some((row) => row.scanStatus !== "clean")) {
|
|
throw new CatalogError(chatErrors.invalidInput, { attachment: "not_deliverable" });
|
|
}
|
|
return fileIds.map((fileId) => ({ id: fileId, mimeType: byId.get(fileId)!.mimeType }));
|
|
}
|
|
|
|
function attachmentLinkRole(mimeType: string): "voice" | "image" | "file" {
|
|
if (mimeType.startsWith("audio/")) return "voice";
|
|
if (mimeType.startsWith("image/")) return "image";
|
|
return "file";
|
|
}
|
|
|
|
async function notifyChatMessageRecipients(
|
|
tx: DbTransactionClient,
|
|
context: ChatRepositoryContext,
|
|
channel: PersistedMemberChannelRow,
|
|
chatId: string,
|
|
message: ChatRealtimeMessage
|
|
): Promise<void> {
|
|
const [members, tenant] = await Promise.all([
|
|
tx.teamChatMember.findMany({
|
|
where: withTenantScope(context.tenantId, { chatId, leftAt: null, userId: { not: context.userId } }),
|
|
select: { userId: true, notificationPref: true },
|
|
}),
|
|
tx.tenant.findUnique({ where: { id: context.tenantId }, select: { slug: true } }),
|
|
]);
|
|
if (!tenant) throw new CatalogError(chatErrors.integrityFailure);
|
|
const mentionedUserIds = new Set(message.mentions.filter((mention) => mention.type === "user").map((mention) => mention.id));
|
|
for (const member of members) {
|
|
const isMentioned = mentionedUserIds.has(member.userId);
|
|
const isDirectMessage = channel.kind === "dm";
|
|
if (!isDirectMessage && !isMentioned && member.notificationPref !== "all_messages") continue;
|
|
const messageKey = isMentioned ? "chat.notifications.mentioned" : isDirectMessage ? "chat.notifications.directMessage" : "chat.notifications.newMessage";
|
|
await notify(
|
|
{
|
|
tenantId: context.tenantId,
|
|
userId: member.userId,
|
|
channel: "IN_APP",
|
|
category: "chat",
|
|
messageKey,
|
|
sourceKey: `chat-message:${message.id}:${member.userId}`,
|
|
payloadMetadata: {
|
|
deeplink: buildChatMessageDeepLink({ tenantSlug: tenant.slug, chatId, messageId: message.id }),
|
|
chatId,
|
|
messageId: message.id,
|
|
},
|
|
},
|
|
tx as unknown as Parameters<typeof notify>[1]
|
|
);
|
|
}
|
|
}
|
|
|
|
async function resolveExistingMessageReplay(
|
|
tx: DbTransactionClient,
|
|
context: ChatRepositoryContext,
|
|
input: NormalizedSendInput,
|
|
eventStreamId: string,
|
|
existing: PersistedMessageRow
|
|
): Promise<SendTopLevelChatMessageResult> {
|
|
const persistedAttachments = await listMessageAttachmentRecords(tx, context.tenantId, [existing.id]);
|
|
const attachmentIds = persistedAttachments.map((attachment) => attachment.fileId);
|
|
const persistedMessage = mapMessage(existing, eventStreamId, attachmentIds);
|
|
if (!isIdenticalMessagePayload(existing, context.userId, input, attachmentIds)) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict);
|
|
}
|
|
|
|
const event = await tx.teamChatEvent.findFirst({
|
|
where: withTenantScope(context.tenantId, {
|
|
chatId: input.chatId,
|
|
entityId: existing.id,
|
|
type: toPersistedChatEventType(CHAT_EVENT_NAMES.messageCreated),
|
|
chat: memberChannelRelation(context),
|
|
}),
|
|
orderBy: { sequence: "asc" },
|
|
select: CHAT_EVENT_SELECT,
|
|
});
|
|
if (!event) {
|
|
throw new CatalogError(chatErrors.integrityFailure);
|
|
}
|
|
|
|
return {
|
|
message: persistedMessage,
|
|
event: mapEvent(event, eventStreamId),
|
|
replayed: true,
|
|
};
|
|
}
|
|
|
|
function mapMemberChannel(
|
|
row: PersistedMemberChannelRow,
|
|
lastMessage: PersistedMessageRow | null,
|
|
participants: readonly ChatParticipantProfileRecord[],
|
|
unread: UnreadProjection,
|
|
eventCursor: string,
|
|
lastMessageAttachmentIds: readonly string[] = []
|
|
): ChatMemberChannelRecord {
|
|
return mapPersistedData(() => {
|
|
const member = row.members[0];
|
|
if (!member) throw new CatalogError(chatErrors.integrityFailure);
|
|
return {
|
|
id: row.id,
|
|
kind: row.kind,
|
|
name: row.name,
|
|
description: row.description,
|
|
projektId: row.projektId,
|
|
isPrivate: row.isPrivate,
|
|
archivedAtIso: row.archivedAt?.toISOString() ?? null,
|
|
lastMessageAtIso: row.lastMessageAt?.toISOString() ?? null,
|
|
eventStreamId: row.eventStreamId,
|
|
eventCursor,
|
|
member: {
|
|
roleInChat: member.roleInChat,
|
|
notificationPreference: member.notificationPref,
|
|
lastReadMessageId: member.lastReadMessageId,
|
|
lastReadAtIso: member.lastReadAt?.toISOString() ?? null,
|
|
isPinned: member.isPinned,
|
|
canWrite: member.writeRevokedAt === null,
|
|
},
|
|
memberCount: row._count.members,
|
|
participants,
|
|
unreadCount: unread.unreadCount,
|
|
hasUnreadMention: unread.hasUnreadMention,
|
|
lastMessage: lastMessage ? mapMessage(lastMessage, row.eventStreamId, lastMessageAttachmentIds) : null,
|
|
};
|
|
});
|
|
}
|
|
|
|
function mapReadReceipt(row: { messageId: string; userId: string; readAt: Date }): ChatMessageReadReceiptRecord {
|
|
return mapPersistedData(() => ({
|
|
messageId: normalizeRequiredIdentifier(row.messageId, "read receipt messageId"),
|
|
userId: normalizeRequiredIdentifier(row.userId, "read receipt userId"),
|
|
readAtIso: row.readAt.toISOString(),
|
|
}));
|
|
}
|
|
|
|
function mapMessage(row: PersistedMessageRow, eventStreamId: string, attachmentIds: readonly string[] = []): ChatRealtimeMessage {
|
|
return mapPersistedData(() => {
|
|
const event = validateChatServerEvent({
|
|
event: CHAT_EVENT_NAMES.messageCreated,
|
|
cursor: `${eventStreamId}:1`,
|
|
requestId: `stored-message-${row.id}`,
|
|
tenantId: row.tenantId,
|
|
chatId: row.chatId,
|
|
occurredAt: row.createdAt.toISOString(),
|
|
data: {
|
|
message: {
|
|
id: row.id,
|
|
clientMessageId: row.clientMessageId,
|
|
authorUserId: row.authorUserId,
|
|
body: row.body,
|
|
bodyFormat: row.bodyFormat,
|
|
parentMessageId: row.parentMessageId,
|
|
mentions: row.mentions,
|
|
attachmentIds: [...attachmentIds],
|
|
linkPreviews: row.linkPreviews,
|
|
createdAt: row.createdAt.toISOString(),
|
|
updatedAt: row.updatedAt.toISOString(),
|
|
editedAt: row.editedAt?.toISOString() ?? null,
|
|
deletedAt: row.deletedAt?.toISOString() ?? null,
|
|
...(row.bodyFormat === "system"
|
|
? {
|
|
systemEvent: {
|
|
kind: row.systemEventKind,
|
|
metadata: row.systemEventMetadata,
|
|
},
|
|
}
|
|
: {}),
|
|
},
|
|
},
|
|
});
|
|
if (event.event !== CHAT_EVENT_NAMES.messageCreated) {
|
|
throw new Error("Stored chat message normalized to an unexpected event type");
|
|
}
|
|
return event.data.message;
|
|
});
|
|
}
|
|
|
|
function mapEvent(row: PersistedEventRow, eventStreamId: string): ChatPersistentEvent {
|
|
return mapPersistedData(() => {
|
|
const event = validateChatServerEvent({
|
|
event: toChatPersistentEventName(row.type),
|
|
cursor: `${eventStreamId}:${row.sequence.toString()}`,
|
|
requestId: row.requestId,
|
|
tenantId: row.tenantId,
|
|
chatId: row.chatId,
|
|
occurredAt: row.occurredAt.toISOString(),
|
|
data: row.data,
|
|
});
|
|
if (!isPersistentChatEvent(event)) {
|
|
throw new Error("Durable chat event normalized to an ephemeral event");
|
|
}
|
|
return event;
|
|
});
|
|
}
|
|
|
|
type NormalizedSendInput = {
|
|
chatId: string;
|
|
clientMessageId: string;
|
|
requestId: string;
|
|
body: string;
|
|
mentions: ChatMention[];
|
|
attachmentFileIds: string[];
|
|
linkPreviews: ChatLinkPreview[];
|
|
};
|
|
|
|
function normalizeSendInput(input: SendTopLevelChatMessageInput): NormalizedSendInput {
|
|
const now = new Date(0).toISOString();
|
|
const linkPreviews = extractChatLinkPreviewPlaceholders(input.body);
|
|
const event = validateChatServerEvent({
|
|
event: CHAT_EVENT_NAMES.messageCreated,
|
|
cursor: "validation:1",
|
|
requestId: input.requestId,
|
|
tenantId: input.tenantId,
|
|
chatId: input.chatId,
|
|
occurredAt: now,
|
|
data: {
|
|
message: {
|
|
id: "pending-message",
|
|
clientMessageId: input.clientMessageId,
|
|
authorUserId: input.userId,
|
|
body: input.body,
|
|
bodyFormat: "markdown",
|
|
parentMessageId: null,
|
|
mentions: extractChatMentions(input.body),
|
|
attachmentIds: input.attachmentFileIds ?? [],
|
|
linkPreviews,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
editedAt: null,
|
|
deletedAt: null,
|
|
},
|
|
},
|
|
});
|
|
if (event.event !== CHAT_EVENT_NAMES.messageCreated) {
|
|
throw new Error("Chat send input normalized to an unexpected event type");
|
|
}
|
|
if (new Set(event.data.message.attachmentIds).size !== event.data.message.attachmentIds.length) {
|
|
throw new Error("attachmentFileIds must not contain duplicates");
|
|
}
|
|
return {
|
|
chatId: event.chatId,
|
|
clientMessageId: event.data.message.clientMessageId,
|
|
requestId: event.requestId,
|
|
body: event.data.message.body,
|
|
mentions: event.data.message.mentions,
|
|
attachmentFileIds: [...event.data.message.attachmentIds].sort(),
|
|
linkPreviews: event.data.message.linkPreviews,
|
|
};
|
|
}
|
|
|
|
function isIdenticalMessagePayload(row: PersistedMessageRow, authorUserId: string, input: NormalizedSendInput, attachmentIds: readonly string[]): boolean {
|
|
return (
|
|
row.chatId === input.chatId &&
|
|
row.authorUserId === authorUserId &&
|
|
row.body === input.body &&
|
|
row.bodyFormat === "markdown" &&
|
|
row.parentMessageId === null &&
|
|
row.deletedAt === null &&
|
|
row.systemEventKind === null &&
|
|
stableJson(row.mentions) === stableJson(input.mentions) &&
|
|
stableJson(row.linkPreviews) === stableJson(input.linkPreviews) &&
|
|
stableJson([...attachmentIds].sort()) === stableJson(input.attachmentFileIds)
|
|
);
|
|
}
|
|
|
|
function stableJson(value: unknown): string {
|
|
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
|
if (value !== null && typeof value === "object") {
|
|
return `{${Object.entries(value)
|
|
.sort(([left], [right]) => left.localeCompare(right))
|
|
.map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
|
|
.join(",")}}`;
|
|
}
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
function normalizeRequiredIdentifier(value: string, label: string): string {
|
|
const normalized = value.trim();
|
|
if (!normalized || normalized.length > 500) {
|
|
throw new Error(`${label} must be a non-empty identifier of at most 500 characters`);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeLimit(value: number | undefined, fallback: number, max: number, label: string): number {
|
|
const normalized = value ?? fallback;
|
|
if (!Number.isInteger(normalized) || normalized < 1 || normalized > max) {
|
|
throw new Error(`${label} must be an integer between 1 and ${max}`);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeMemberChannelListInput(input: ListMemberChannelsInput): NormalizedMemberChannelListInput {
|
|
if (input.query !== undefined && typeof input.query !== "string") {
|
|
throw new Error("channel query must be a string");
|
|
}
|
|
const query = (input.query ?? "").trim().replace(/\s+/g, " ");
|
|
if (query.length > MAX_CHANNEL_QUERY_LENGTH || query.includes("\0")) {
|
|
throw new Error(`channel query must be at most ${MAX_CHANNEL_QUERY_LENGTH} characters`);
|
|
}
|
|
|
|
const view = input.view ?? "all";
|
|
if (typeof view !== "string" || !MEMBER_CHANNEL_LIST_VIEWS.has(view as ChatMemberChannelListView)) {
|
|
throw new Error("channel view is invalid");
|
|
}
|
|
if (input.includeArchived !== undefined && typeof input.includeArchived !== "boolean") {
|
|
throw new Error("includeArchived must be a boolean");
|
|
}
|
|
const includeArchived = input.includeArchived ?? false;
|
|
const filterKey = JSON.stringify([
|
|
normalizeRequiredIdentifier(input.tenantId, "tenantId"),
|
|
normalizeRequiredIdentifier(input.userId, "userId"),
|
|
query,
|
|
view,
|
|
includeArchived,
|
|
]);
|
|
|
|
return {
|
|
query,
|
|
view: view as ChatMemberChannelListView,
|
|
includeArchived,
|
|
limit: normalizeLimit(input.limit, DEFAULT_CHANNEL_LIMIT, MAX_CHANNEL_LIMIT, "channel limit"),
|
|
afterCursor: parseMemberChannelCursor(input.afterCursor, filterKey),
|
|
filterKey,
|
|
};
|
|
}
|
|
|
|
function escapeLikePattern(value: string): string {
|
|
return value.replace(/[!%_]/g, (character) => `!${character}`);
|
|
}
|
|
|
|
function parseMemberChannelCursor(value: string | undefined, expectedFilterKey: string): MemberChannelCursor | null {
|
|
if (value === undefined) return null;
|
|
if (typeof value !== "string" || !value || value.length > MAX_CHANNEL_CURSOR_LENGTH || !/^[A-Za-z0-9_-]+$/.test(value)) {
|
|
throw new Error("channel cursor has an invalid encoding");
|
|
}
|
|
|
|
const decoded = Buffer.from(value, "base64url");
|
|
if (decoded.toString("base64url") !== value) {
|
|
throw new Error("channel cursor is not canonically encoded");
|
|
}
|
|
const parsed: unknown = JSON.parse(decoded.toString("utf8"));
|
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
throw new Error("channel cursor has an invalid payload");
|
|
}
|
|
const record = parsed as Record<string, unknown>;
|
|
if (
|
|
record.v !== 1 ||
|
|
typeof record.filterKey !== "string" ||
|
|
typeof record.isPinned !== "boolean" ||
|
|
(record.lastMessageAtIso !== null && typeof record.lastMessageAtIso !== "string") ||
|
|
typeof record.createdAtIso !== "string" ||
|
|
typeof record.id !== "string" ||
|
|
Object.keys(record).sort().join(",") !== "createdAtIso,filterKey,id,isPinned,lastMessageAtIso,v"
|
|
) {
|
|
throw new Error("channel cursor has an invalid payload");
|
|
}
|
|
if (record.filterKey !== expectedFilterKey) {
|
|
throw new Error("channel cursor belongs to another filter");
|
|
}
|
|
|
|
const createdAt = parseCursorTimestamp(record.createdAtIso, "channel cursor createdAt");
|
|
const lastMessageAt = record.lastMessageAtIso === null ? null : parseCursorTimestamp(record.lastMessageAtIso, "channel cursor lastMessageAt");
|
|
return {
|
|
chatId: normalizeRequiredIdentifier(record.id, "channel cursor id"),
|
|
isPinned: record.isPinned,
|
|
lastMessageAt,
|
|
createdAt,
|
|
filterKey: record.filterKey,
|
|
};
|
|
}
|
|
|
|
function parseCursorTimestamp(value: string, label: string): Date {
|
|
const parsed = new Date(value);
|
|
if (!Number.isFinite(parsed.getTime()) || parsed.toISOString() !== value) {
|
|
throw new Error(`${label} has an invalid timestamp`);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
function encodeMemberChannelCursor(filterKey: string, row: MemberChannelCandidateRow): string {
|
|
return mapPersistedData(() => {
|
|
if (
|
|
typeof row.isPinned !== "boolean" ||
|
|
!(row.createdAt instanceof Date) ||
|
|
!Number.isFinite(row.createdAt.getTime()) ||
|
|
(row.lastMessageAt !== null && (!(row.lastMessageAt instanceof Date) || !Number.isFinite(row.lastMessageAt.getTime())))
|
|
) {
|
|
throw new Error("Invalid channel cursor projection");
|
|
}
|
|
return Buffer.from(
|
|
JSON.stringify({
|
|
v: 1,
|
|
filterKey,
|
|
isPinned: row.isPinned,
|
|
lastMessageAtIso: row.lastMessageAt?.toISOString() ?? null,
|
|
createdAtIso: row.createdAt.toISOString(),
|
|
id: normalizeRequiredIdentifier(row.chatId, "channel cursor id"),
|
|
}),
|
|
"utf8"
|
|
).toString("base64url");
|
|
});
|
|
}
|
|
|
|
function parseMessageCursor(value: string | undefined, expectedChatId: string): MessageCursor | null {
|
|
if (value === undefined) return null;
|
|
if (!value || value.length > MAX_MESSAGE_CURSOR_LENGTH || !/^[A-Za-z0-9_-]+$/.test(value)) {
|
|
throw new Error("message cursor has an invalid encoding");
|
|
}
|
|
|
|
const decoded = Buffer.from(value, "base64url");
|
|
if (decoded.toString("base64url") !== value) {
|
|
throw new Error("message cursor is not canonically encoded");
|
|
}
|
|
const parsed: unknown = JSON.parse(decoded.toString("utf8"));
|
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
throw new Error("message cursor has an invalid payload");
|
|
}
|
|
const record = parsed as Record<string, unknown>;
|
|
if (
|
|
record.v !== 1 ||
|
|
typeof record.chatId !== "string" ||
|
|
typeof record.createdAtIso !== "string" ||
|
|
typeof record.id !== "string" ||
|
|
Object.keys(record).sort().join(",") !== "chatId,createdAtIso,id,v"
|
|
) {
|
|
throw new Error("message cursor has an invalid payload");
|
|
}
|
|
if (normalizeRequiredIdentifier(record.chatId, "message cursor chatId") !== expectedChatId) {
|
|
throw new Error("message cursor belongs to another channel");
|
|
}
|
|
const createdAt = new Date(record.createdAtIso);
|
|
if (!Number.isFinite(createdAt.getTime()) || createdAt.toISOString() !== record.createdAtIso) {
|
|
throw new Error("message cursor has an invalid timestamp");
|
|
}
|
|
return { createdAt, id: normalizeRequiredIdentifier(record.id, "message cursor id") };
|
|
}
|
|
|
|
function encodeMessageCursor(chatId: string, row: Pick<PersistedMessageRow, "createdAt" | "id">): string {
|
|
return mapPersistedData(() =>
|
|
Buffer.from(
|
|
JSON.stringify({
|
|
v: 1,
|
|
chatId: normalizeRequiredIdentifier(chatId, "message cursor chatId"),
|
|
createdAtIso: row.createdAt.toISOString(),
|
|
id: normalizeRequiredIdentifier(row.id, "message cursor id"),
|
|
}),
|
|
"utf8"
|
|
).toString("base64url")
|
|
);
|
|
}
|
|
|
|
export function parseChatMessageCursor(value: string | undefined, expectedChatId: string): { createdAt: Date; id: string } | null {
|
|
return parseMessageCursor(value, expectedChatId);
|
|
}
|
|
|
|
export function encodeChatMessageCursor(chatId: string, row: { readonly createdAt: Date; readonly id: string }): string {
|
|
return encodeMessageCursor(chatId, row);
|
|
}
|
|
|
|
function mapPublicInput<TResult>(operation: () => TResult): TResult {
|
|
try {
|
|
return operation();
|
|
} catch (error) {
|
|
if (error instanceof CatalogError) throw error;
|
|
throw new CatalogError(chatErrors.invalidInput);
|
|
}
|
|
}
|
|
|
|
function mapPersistedData<TResult>(operation: () => TResult): TResult {
|
|
try {
|
|
return operation();
|
|
} catch (error) {
|
|
if (error instanceof CatalogError) throw error;
|
|
throw new CatalogError(chatErrors.integrityFailure);
|
|
}
|
|
}
|
|
|
|
function mapPersistedCursor(streamId: string, sequence: bigint): string {
|
|
return mapPersistedData(() => normalizeChatEventCursor(`${streamId}:${sequence.toString()}`));
|
|
}
|
|
|
|
function isMessageIdempotencyUniqueError(error: unknown): boolean {
|
|
if (!error || typeof error !== "object" || !("code" in error) || (error as { code?: unknown }).code !== "P2002") return false;
|
|
const target = (error as { meta?: { target?: unknown } }).meta?.target;
|
|
const fields = ["tenantId", "authorUserId", "clientMessageId"];
|
|
if (Array.isArray(target)) {
|
|
const targetFields = target.filter((entry): entry is string => typeof entry === "string");
|
|
return targetFields.length === fields.length && fields.every((field) => targetFields.includes(field));
|
|
}
|
|
return typeof target === "string" && fields.every((field) => target.includes(field));
|
|
}
|